Vue中父子组件传值,父子组件方法调用的一个案例

221 阅读1分钟

1.父组件

<template>
  <div class="parent">
    <son ref="son" :sonNumber="parentNumber" :parentMethod="parentMethod" @sendSonNumber="receiveSonNumber" @sonCallParentFun="parentFun"></son>
    <button @click="handleSonNumber">点击更改子组件的值</button>
    <button @click="callSonFun">点击调用子组件的方法</button>
  </div>
</template>

<script>
import son from "./son.vue";

export default {
  name: "parent",
  components: {
    son,
  },
  data() {
    return {
      parentNumber: 1,
    };
  },
  methods: {
    // 更改子组件的number值
    handleSonNumber() {
      this.parentNumber++
    },
    // 在父组件中的子标签中监听子组件的sendSonNumber自定义事件,并添加一个响应该事件的处理方法receiveSonNumber,接收子组件传递来的number值
    receiveSonNumber(num) {
      this.parentNumber = num
    },
    // 使用$refs父组件调用子组件的方法
    callSonFun() {
      this.$refs.son.sonFun()
    },
    // 在父组件中的子标签中监听子组件的sonCallParentFun自定义事件,并调用一个响应该事件的父组件的方法parentFun
    parentFun() {
      this.parentNumber = 99
    },
    // 父组件的方法
    parentMethod() {
      this.parentNumber = 200
    },
  },
};
</script>

<style scoped>
.parent {
  background: #ffbece;
}
</style>

2. 子组件

<template>
  <div class="son">
    <span style="color:#ff0000;">{{ sonNumber }}</span>
    <button @click="clickSon">点击按钮向父组件传值</button>
    <button @click="callParentFun">点击调用父组件的方法1</button>
    <button @click="childMethod">点击调用父组件的方法2</button>
  </div>
</template>

<script>
export default {
  name: "son",
  props: {
    sonNumber: {
      type: Number,
      default: 0,
    },
    parentMethod: {
      type: Function,
      default: null,
    },
  },
  data() {
    return {};
  },
  methods: {
    // 子组件通过$emit向父组件传值
    clickSon() {
      this.$emit('sendSonNumber',50)
    },
    // 子组件方法
    sonFun() {
      this.$emit('sendSonNumber',11)
    },
    // 点击通过$emit调用父组件的方法
    callParentFun() {
      this.$emit('sonCallParentFun')
    },
    childMethod() {
      this.parentMethod()
    },
  },
};
</script>

<style scoped>
.son {
  background: #bef2ff;
}
</style>