BootstrapVue项目中父组件点击按钮触发子组件方法的实现问询
实现方案(无需watch)
你现有代码存在两处笔误需要先修正:
- 父组件给子组件传值时绑定的变量名写错:你在data中定义的变量是
propsIndex,但模板里写的是indexProps - 父子组件的prop命名不统一:父组件传的prop名是
indexProps,子组件声明接收的是propsIndex,两边不一致会导致子组件无法正常拿到值
最优方案:通过ref直接调用子组件方法
父组件点击按钮时主动触发对应子组件的方法,完全不需要监听属性变化,实现逻辑最直接,性能也最高。
修改后的parent.vue代码
<template> <div v-for="(id, index) in inputs" :key="index"> <b-button @click="deleteViaIndex(index)">Delete</b-button> <!-- 给子组件绑定动态ref获取对应实例,统一prop命名 --> <child :propsIndex="propsIndex" :ref="`child-${index}`" /> </div> <div> <b-button @click="addInput()">Add Input</b-button> </div> </template> <script> export default { methods: { deleteViaIndex(index) { this.propsIndex = index; // 获取对应子组件实例,主动调用目标方法 const targetChild = this.$refs[`child-${index}`]?.[0] targetChild && targetChild.deleteViaParentIndex() }, addInput() { this.inputs.push({}) }, }, data() { return { inputs: [{}], propsIndex: '', } } } </script>
child.vue无需额外修改
你的子组件原有代码可以直接复用,deleteViaParentIndex方法内可以正常读取this.propsIndex的值使用:
props: ["propsIndex"], methods: { deleteViaParentIndex() { // 此处可以正常拿到父组件传递的index值 console.log(this.propsIndex) // 补充你的业务逻辑即可 } }
补充说明
如果后续你的业务场景迭代为多层组件嵌套、不方便用ref直接调用的情况,也可以使用Vue实例作为事件总线传递触发信号,父子组件监听对应事件触发方法即可,不过当前纯父子组件通信的场景下用ref是逻辑最清晰的实现。
内容的提问来源于stack exchange,提问作者patrick96
相关产品推荐
相关产品推荐

