Vue 父子组件传递数据

Vue父组件给子组件传值:

父组件:

<template>
  <div class="father">
    {{ message }}
    <Son v-bind:message="message"></Son>
  </div>
</template>

<script>
//导入Son组件
import Son from "./Son";
export default {
  name: "father",
  data() {
    return {
      message: "hello, father",
    };
  },
  components: {
    Son,
  },
  methods: {},
};
</script>

  

子组件:

<template>
  <div class="son">子元素: {{ message }}</div>
</template>

<script>
export default {
  name: "son",
  props: {
    message: {
      type: String,
      default: "",
    },
  },
  data() {
    return {};
  },
};
</script>

父组件传子组件,props是关键;

 

Vue子组件给父组件传值:

 父组件:

<template>
  <div class="father">
    <p>{{ message }}</p>
    <!-- @receiveData="receiveData"一定要写在子标签上 -->
    <Son v-bind:message="message" @receiveData="receiveData"></Son>
  </div>
</template>

<script>
//导入Son组件
import Son from "./Son";
export default {
  name: "father",
  data() {
    return {
      message: "hello, father",
    };
  },
  components: {
    Son,
  },
  methods: {
    /**
     * 接收子组件数据
     */
    receiveData(message) {
      this.message = message;
    },
  },
};
</script>

  

子组件:

<template>
  <div class="son">
    <p>子元素: {{ message }}</p>
    <button @click="transferData">click</button>
  </div>
</template>

<script>
export default {
  name: "son",
  props: {
    message: {
      type: String,
      default: "",
    },
  },
  data() {
    return {};
  },
  methods: {
    transferData() {
      //调用父组件接收子组件数据方法,传递数据
      this.$emit("receiveData", "son数据:hello, father!");
    },
  },
};
</script>

子组件传父组件,emit方法是关键;

posted @ 2020-08-09 15:15  尘世间迷茫的小书童  阅读(190)  评论(0编辑  收藏  举报