组件通讯常用方法为:props,$emit,$on,$refs,$attrs,$listeners,eventbus,vuex;
刚开始看好乱,感觉绕的很,总是分不清绑定的顺序;后来总结了一下,感觉容易了很多。那个组件的数据变量,方法,写在那个标签里面,若果要引用外部变量,方法,必须使用写在v-bind,或是v-on的绑定“=”后面;
父组件传值给子组件props,$refs,$attrs;
1.props传值
特点:数据具有联动性(父变,子也变;子变父不变),不能跨级,只能父及传子及数据;
<div id="app"></div>
<script type="text/javascript">
Vue.component("component-parent", {
data() {
return{
parentMsg:"父组件数据"
}
},
template:`<div>
<h3>我是父组件,数据为:{{parentMsg}}</h3>
<component-child :msg='parentMsg'></component-child>
</div>`
})
Vue.component("component-child", {
props:{
msg:String //传递的数据类型为string
},
data() {
return{
childMsg:this.msg
}
},
template:`<p>我是子组件,我接收的收据是:{{childMsg}}</p>`
})
new Vue({
el:"#app",
template:"<component-parent></component-parent>"
})
</script>
注意:最好具体化props传递的值;
2.$refs
特点:利用ref标识组件,通过事件传参吧数据传给子组件,数据相互独立
<div id="app"></div>
<script>
Vue.component("parent",{
data(){
return{
parentMsg:"我是父组件数据parent"
}
},
template:`<div>
<h3>父组件:{{parentMsg}}</h3>
<button @click="send">点击改变西面子组件的数据</button>
<button @click="changSlef">点击改变父组件数据,但子组件的数据不变哦</button>
<child ref="child"></child>
</div>`,
methods:{
send:function(){
this.$refs.child.changeMsg(this.parentMsg);
},
changSlef:function(){
this.parentMsg="我是父组件数据,我发生改变了"
}
}
})
Vue.component("child",{
data() {
return {
childMsg:"我是子组件数据child"
}
},
template:`<div>
<h4>子组件:{{ childMsg }}</h4>
</div>`,
methods: {
changeMsg:function(val){
this.childMsg=val;
}
},
})
new Vue({
el:"#app",
data() {
return {
msg1:"传给child1的数据",
msg2:"传给child2的数据",
msg3:"传递给child3的值"
}
},
template:`<div>
<parent></parent>
</div>`
})
</script>
3.$attrs
特点:通过绑定属性,来实现传值;可以实现,父传子,孙组件;
注意:$attrs是vue2.4版本提出的方法,使用是注意版本号
<div id="app"></div>
<script>
Vue.component("component-c",{
inheritAttrs:false, //继承所有的父组件属性(除了prop传递的属性、class 和 style )
template:`<div>
<h5 >c组件:{{$attrs.c}}</h5>
</div>`
})
Vue.component("component-b",{
inheritAttrs:false, //继承所有的父组件属性(除了prop传递的属性、class 和 style )
template:`<div>
<h2 >$attrs传递的值:{{$attrs.b}}</h2>
<component-c v-bind="$attrs"></component-c>
</div>`
//v-bind="attrs";绑定属性,是c组件可以接收a逐渐传值
})
Vue.component("component-a",{
data () {
return {
aMsg:"组件a",
msgB:"组件a传给b的值",
msgC:"组件a传给c的值",
d:"默认值"
}
},
template:`
<div>
<h1>a组件:{{ aMsg }}</h1>
<component-b name="组件a" title="attr传值" :b="msgB" :c="msgC" ></component-b>
</div>
`
})
var app=new Vue({
el:'#app',
template:`
<div>
<component-a></component-a>
</div>
`
})
</script>
网友评论