父传子:通过绑定一个属性,例如:content=“要传的值”
子传父:$emit
兄弟传值:通过bus主线把需要传值的组件连接起来
父子传值:简而言之就是父组件向子组件传值,子组件向父组件传值
下面以待办事项案例为例
逻辑:输入框的值——>代办事项父组件——>代办事项子组件
效果图:
注册两个组件,一个为代办组件,一个为已办组件
props:使用来获取父组件传的值
template:组件内的内容,看以看成子组件
//创建全局组件/待办组件
Vue.component("todo-item",{
props:['content'], //外部传过来的值
template:"{
{content}} ", //组件模板
})
//创建全局组件/已办组件
Vue.component("done-item",{
props:['content'],
template:"{
{content}} "
})
然后在html中引用组件
:content:通过属性的形式传值给子组件
<div id="app">
<input type="text" v-model="inputvalue" />
<button v-on:click="handlebtnclick">添加待办事项</button>
<p>待办事项</p>
<ul>
<todo-item :content="item"
:key="index"
v-for="(item,index) in todolist"
v-on:delete="handleitemclick">
</todo-item>
</ul>
<p>已办事项</p>
<ul>
<done-item :content="item"
:key="index"
v-for="(item,index) in donelist">
</done-item>
</ul>
</div>
我们写个方法,当点击按钮时,把输入框的内容添加到代办事项中
逻辑:输入框的值——>代办事项父组件——>代办事项子组件
handlebtnclick:function(){
if(this.inputvalue){
this.todolist.push(this.inputvalue) //把文本框内容添加到列表中
this.inputvalue = ''; //清空文本框
}
}
假设我点击待办事项中的一项,他就会从代办事项中消失,出现在已办事项中
逻辑:待办事项点击的值——>父组件(待办组件)——>传给已办事项和删除代办事项的值
效果图:
我们可以使用**$emit**把子组件的数据传回父组件
handleitemclick:function(){
this.$emit('delete',this.index,this.content);
}
然后对组件绑定的值进行操作
1:删除代办项数组的值
2:给已办项数组添加值
handleitemclick:function(index,content){
this.donelist.push(content) //把点击的代办事项添加到已办事项
this.todolist.splice(index,1); //把点击的代办事项清除
}
兄弟传值:简而言就是同级别的组件互相传值传值
逻辑:
点击兄弟组件1——>传值给兄弟组件2
点击兄弟组件2——>传值给兄弟组件1
先定义组件
Vue.component('child-brother1',{
props:['content'],
data:function(){
return{
selfcontent:this.content //把父组件的值传给selfcontent,再绑定子组件
}
},
template:`
兄弟1
{
{selfcontent}}
`
})
Vue.component('child-brother2',{
props:['content'],
data:function(){
return{
selfcontent:this.content //把父组件的值传给selfcontent,再绑定子组件
}
},
template:`
兄弟2
{
{selfcontent}}
`
})
然后在html中引用组件,并实例化vue
<div id="app">
<child-brother1 content="我是要传的值">child-brother1>
<child-brother2 content="">child-brother2>
div>
var vm = new Vue({
el:'#app'
})
下面重点来了
定义一条主线bus,主要用来连接两个组件
Vue.prototype.bus = new Vue();
接着通过$emit向外触发一个change事件,change事件触发时可以传递数据
this.bus.$emit('change',this.content)
然后在周期函数钩子mounted中写个监听
当监听到change事件出发时,获取兄弟组件传过来的值
function(){
var this_ = this
this.bus.$on('change',function(e){
//监听/当change事件激活,获取传过来的值,并赋值给自身
this_.selfcontent = e //之所以不是赋值给content而是selfcontent,是因为content来源于父组件,直接更改会报错
})
}
父子传值完整代码:点击访问GitHub代码地址
兄弟传值完整代码:点击访问GitHub代码地址