一:比较直接的方法(缺点:耦合度高,如若子组件方法改变,父组件要跟的去改变)
1 父组件获取子组件(详细代码见$ref)
在父级中添加ref:<Search @search="handleSearch" placeholder="搜索频道" ref="cc"/>
使用时:分别为获取子组件的变量及方法:
console.log(this.$refs.cc.searchVal)
console.log(this.$refs.cc.toParent())
2 子组件获取父组件:使用属性(详细代码见博文vue组件-属性及插槽)
(1)在父组件中添加属性,
(2)在子组件中添加props
二:使用$emit,$on(针对事件传递)
1 父组件传子组件(子组件传父组件同理)
父组件重要代码片段:
template中:
<input type="text" @click="fn()"/>
<child/ ref="cc">
methods中:
fn(){
this.$refs.cc.$emit("add",7);//第一个参数为方法名,第二个参数为传的参数
}
子组件不添加任何代码(即子组件可以不添加任何处理)不会报错。
子组件如果需要用,在子组件中:
created中:
this.$on("add",function (n){
this.num += n;
})
三 vueX(棒棒哒:全局,统一,单一)
1 优点:
(1)数据跨组件共享
(2)防止数据意外修改
(3)调试,测试
2 详细内容见Vuex模块