Vue子组件调用父组件事件的三种方法

1. 在子组件中通过this.$parent.event来调用父组件的方法,data参数可选

<template>
  <div>
    <h1>我是父组件</h1>
    <child />
  </div>
</template>
<script>
  import child from '@/components/child';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod(data) {
        console.log('我是父组件方法');
      }
    }
  };
</script>
<template>
  <div>
    <h1>我是子组件</h1>
    <button @click="childMethod(data)">点击</button>
  </div>
</template>
<script>
  export default {
    methods: {
      childMethod() {
        this.$parent.fatherMethod(data);
        console.log('调用父组件方法')
      }
    }
  };
</script>

2.父组件使用v-bind绑定一个变量(v-bind:变量名="值"),子组件用props接收(与created同级)

<template>
  <div>
    这是父组件
    <child :parentHandler="parentHandler" />
  </div>
</template>
<script>
import child from "@/components/child";
export default {
  components: { child },
  data() {
    return {};
  },
  methods: {
    parentHandler() {
      console.log("这是父组件的方法");
    },
  },
};
</script>
<template>
  <div>
    这是子组件
    <button @click="handler">这是子组件的按钮</button>
  </div>
</template>
<script>
export default {
  props: {
    parentHandler: {
      type: Function,
      default: () => {
        return Function;
      },
    },
    //parentHandler: {
    //   type: Object,
    //   default: () => {
    //     return {}
    //   },
    //},
    // parentHandler: {
    //   type: Boolean,
    //   default: true,
    // },
    // parentHandler: {
    //   type: Array,
    //   default: () => {
    //     return []
    //   },
    // },
    // parentHandler: {
    //   type: String,
    //   default: '',
    // },
  },
  methods: {
    handler() {
      this.parentHandler();
    },
  },
};
</script>

3.使用$refs传值

<template>
  <div>
    <h3>这是父组件</h3>
    <button @click="setChildInfo">向子组件传值</button>
    <h3>这是父组件中引用的子组件</h3>
    <child ref="child"></child>
  </div>
</template>

<script>
//子组件地址(仅供参考),具体以实际项目目录地址为准
import child from "./Child.vue";
export default {
  components: {
    child: child
  },
  data() {
    return {};
  },
  methods: {
    // 向子组件传值
    setChildInfo() {
      this.$refs.child.cInfo = "c2";
      //this.$refs.child.open("c2");
    }
  }
};
</script>
<template>
  <div>
    <p>收到父组件数据:{
   
   { cInfo }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cInfo: "c1"
    };
  },
  methods: {
    //open(data) {
    //  console.log(data);
    //},
  },
};
</script>

猜你喜欢

转载自blog.csdn.net/m0_37878884/article/details/129037706