vue中实现由子组件向父组件传值,有以下两种简单方式
①父组件中在子组件上面绑定函数,然后子组件使用props接收,然后子组件在调用此函数时传参,那么父组件就可以在methods中的回调函数中接收到了这个参数。
②父组件中在子组件上面绑定自定义事件,然后子组件使用下面的API:
this.$emit(“自定义事件名”, params);
那么父组件就可以在自定义事件的回调函数中接收到这个参数。
②相比于①的优点是无需在子组件中使用props进行接收,并且显得更高级。
自定义事件解绑的三种方式:
单事件:this.$off('自定义事件名称');
多事件:this.$off(['自定义事件A','自定义事件B']);
全部事件:this.$off();
自定义事件的两种使用方式:
1、常规方式
父组件中:<children @customEvents = 'methodsEvent' />
子组件中:this.$emit(“customEvents ”, params);
父组件中:methods: {
methodsEvent(params) {
console.log('子组件传递过来的参数为', params)
}
}
2、ref方式
父组件中:<children ref = 'childrenRef' />
子组件中:this.$emit(“customEvents ”, params);
父组件中:this.$on("customEvents", (params)=> { // 此处应使用箭头函数
console.log('子组件传递过来的参数为', params)
})