欢迎来到 Renly 的博客园,如果小伙伴们有需要讲解的技术,可以给笔者发消息或邮件留言!【renlywen@foxmail.com】

vue父子组件的传值总结

一、创建父子组件

父组件:parent.vue

<template>
  <div class="parent">
    <h3>我是父组件</h3>
    <p>父组件的年龄是:{parentAge}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      parentAge: 50
    };
  }
};
</script>

子组件:

<template>
  <div class="child">
    <h3>我是子组件</h3>
    <p>子组件的年龄是:{{childAge}}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      childAge: 27
    };
  }
};
</script>

二、父组件给子组件传值

<template>
  <div class="parent">
    <h3>我是父组件,我想告诉我的子组件,我的年龄值是:{{parentAge}}</h3>
    <h3>我要通过v-bind(即简写":")语法糖绑定一个属性deliverParentAge,将父组件的值传递到子组件中</h3>
    <!-- 下面就是我的子组件 -->
    <my-child :deliverParentAge="parentAge"></my-child>
  </div>
</template>

<script>
import MyChild from "./Child";
export default {
  components: { MyChild },
  data() {
    return {
      parentAge: 49
    };
  }
};
</script>

子组件通过props属性,在子组件中接收父组件传过来的值

<template>
  <div class="child">
    <h5>我是子组件,我可以通过属性props来接收父组件传过来的年龄值是:{{deliverParentAge}}</h5>
  </div>
</template>

<script>
export default {
  data() {
    return {
      childAge: 27
    };
  },
  props: {
    deliverParentAge: Number
  }
};
</script>

3、子组件给父组件传值

<template>
  <div class="child">
    <h5>我是子组件,我可以通过属性props来接收父组件传过来的年龄值是:{{deliverParentAge}},这是一个数字类型</h5>
    <h5>并且,我要告诉他,他今年生日已经过了,所以他的年龄应该<button @click="AddAge">加1</button></h5>
    下面我要通过this.$emit方法提交一个事件addParentAge,告诉我的父组件,他的实际年龄
  </div>
</template>

<script>
export default {
  data() {
    return {
      childAge: 27
    };
  },
  props: {
    deliverParentAge: Number
  },
  // 新建一个计算属性,将父组件原来的值加1
  computed: {
    parentActualAge() {
      return this.deliverParentAge + 1;
    }
  },
  methods: {
    AddAge() {
      this.$emit("addParentAge", this.parentActualAge);
    }
  }
};
</script>

父组件通过语法糖v-on(即简写为“@”)来监听子组件提交的事件addParentAge

<template>
  <div class="parent">
    <h3>我是父组件,我想告诉我的子组件,我的年龄值是:{{parentAge}}</h3>
    <h3>我要通过v-bind(即简写":")语法糖绑定一个属性parentAge,告诉子组件我的年龄值是:{{parentAge}}</h3>
    <!-- 下面就是我的子组件 -->
    <my-child :deliverParentAge="parentAge"
            @addParentAge="handleAddParentAge"></my-child>
    <h3>通过监听子组件提交的事件addParentAge,我知道到了自己的实际年龄应该是:{{parentAge+1}},并通过方法handleAddParentAge,在控制台打印出我的真实年龄</h3>

  </div>
</template>

<script>
import MyChild from "./Child";
export default {
  components: { MyChild },
  data() {
    return {
      parentAge: 49
    };
  },
  methods: {
    handleAddParentAge(actualAge) {
      console.log("父组件的实际年龄是:", actualAge);
    }
  }
};
</script>
posted @ 2020-08-24 17:13  Renly_wen  阅读(247)  评论(0编辑  收藏  举报
……