vue中组件之间如何传参及组件间如何触发方法
一、父子组件
1、如何传参
1)父组件向子组件传参
方法一:props
- 父组件
- 子组件
方法二:$children
父组件
this.msg2=this.$children[0].msg
2)子组件向父组件传参
方法一:$emit
- 父组件
- 子组件
方法二:$parent
子组件
this.msg22 = this.$parent.msg2;
2、如何调用方法
1)父组件触发子组件方法
$emit
和 $on
父组件
子组件
2)子组件触发父组件方法
方法一:this.$parent.event
父组件
子组件
方法二:$emit
父组件
子组件
方法三:props
父组件
子组件
二、非父子组件
方法一:创建一个公用的 bus (vue 实例)
main.js文件
发送组件一
接收组件二
方法二:vuex
store/index文件
组件中使用:
this.$store.state.name
修改:
handleNameClick (name) {
this.$store.dispatch('changeName', name)
//派发一个名字叫 changeName 的 Actions,并把 name 传过去
}
//或者
handleNameClick (name) {
this.$store.commit('changeName', name)
//派发一个名字叫 changeName 的 mutation,并把 name 传递过去。
//所以上面的 store 里可以把 Actions 给删除了。
}