父组件向子组传值
父组件
<!--:placeholder是想子组件传值的属性,可以自定义-->
<!--searchText此事件名必须要跟子组件传递过来的事件名一样-->
<SearchComponents @searchText='getChildData' :placeholder="startText" />
import SearchComponents from '@/components/SearchComponents.vue'
export default{
name:'Home',
components:{//注册组件
SearchComponents
},
data(){
return{
startText:'向子组件传值'
}
},
methods:{
//这样就可以接受到子组件传递过来的值
getChildData(e){
console.log(e);
}
}
}
子组件
<div class="web">
<div class="search">
<!--:placeholder属性要跟父组件中的一样,不然不会报错-->
<input type="text"
:placeholder="keyword"
v-model.trim="searchText">
</div>
<i class="iconfont icon-sousuo search-icon" @touchstart='searchData'></i>
</div>
//通过props来接受父组件传递过来的值
export default{
name:'search',
//验证父组件穿过来的值
props:{
keyword: {
type: String,//声明传入的类型
default: '请输入关键字',//默认显示
validator:function(value){
return value//返回传入的值
}
},
}
//不需要认证父组件传过来的值
props:["keyword"],
data(){
searchText:''
},
methods:{
searchData(){
//子组件通过$emit方法向父组件传递,searchText就是父组件接受时触发的事件
this.$emit('searchText',this.searchText);
}
}
}
通过$emit 和 $on
这种方法通过一个空的Vue实例作为中央事件总线(事件中心),用它来触发事件和监听事件,巧妙而轻量地实现了任何组件间的通信,包括父子、兄弟、跨级组件之间的传值
//新建bus src/bus.js
import Vue from 'vue'
export default new Vue( )
组件B向组件C传值
<template>
<div @click="changB">
组件B
</div>
</template>
<script>
//引入中间件bug
import bug from "@/bus.js";
export default{
name:'B',
methods:{
changB(){
//bug也可以在main.js中注册,这样就不用每个组件进行引入
//main.js
/*
import bug from '@/bus.js';
Vue.prototype.bug = bug;
使用办法一样
*/
bug.$emit('brotherB','兄弟组件B传值给兄弟组件C')
}
},
}
</script>
组件C接受组件B传过来的值
在接收参数的组件中也要引入bug.js
<template>
<div @click="changeC">
组件C
</div>
</template>
<script>
import bug from "@/bus.js";
export default{
methods:{
changeC(){
this.$bug.$emit('brotherC','组件C向组件B传值')
}
},
//mounted钩子函数里面获取组件B传过来的值
mounted(){
bug.$on('brotherB',res=>{
console.log(res)
})
}
}
</script>