vue2父子組件通信一般有3種方式
1诊沪、props+自定義事件
2哥攘、props+sync修飾符
3虱颗、props+v-model
因為第一種方式罗丰,還需要在父組件methods中聲明方法去改變值,顯得比較麻煩挠将。
所以推薦使用第二種或者第三種方式胳岂。
如果是改變多個值就使用第二種方法,如果只是改變一個值那么就使用第三種方法舔稀。
方法一:props+自定義事件
父組件 Demo
<div id="demo">
<input type="text" v-model="name">
<!--子組件傳遞過來的參數(shù)由自定義事件綁定的方法接收-->
<demo-child :nameFather="name" @newData="newName"></demo-child>
</div>
import DemoChild from '@/components/DemoChild'
export default {
data(){
return {
name:'nihao'
}
},
components:{
DemoChild
},
methods:{
//因此參數(shù)value是 '這是子組件傳遞過來的數(shù)據(jù)'
newName(value){
this.name=value
}
}
}
子組件 DemoChild
<template>
<div id="demo_child">
<p @click="change">DemoChild組件:{{nameFather}}</p>
</div>
</template>
export default {
//接收屬性nameFather
props:{
nameFather: String
},
methods:{
change(){
//觸發(fā)父組件中的自定義事件newData , this.$emit('需要觸發(fā)的自定義事件' [,'需要傳遞的參數(shù)'])
this.$emit('newData','這是子組件傳遞過來的數(shù)據(jù)')
}
}
}
方法二:props+sync修飾符
父組件 Demo
<div id="demo">
<input type="text" v-model="name">
<demo-child :nameFather.sync="name"></demo-child>
</div>
import DemoChild from '@/components/DemoChild'
export default {
data(){
return {
name:'nihao'
}
},
components:{
DemoChild
}
}
是子組件 DemoChild
<div id="demo_child">
<p @click="change">DemoChild組件:{{nameFather}}</p>
</div>
export default {
props:{
nameFather: String
},
methods:{
change(){
//觸發(fā)父組件自定義屬性nameFather的更新乳丰,this.$emit('update:父組件需要更新的自定義屬性','更新后的屬性值')
this.$emit('update:nameFather','這是子組件傳遞過來的數(shù)據(jù)')
}
}
}
方法三:props + v-model
父組件 Demo
<div id="demo">
<input type="text" v-model="name">
<demo-child v-model="name"></demo-child>
</div>
import DemoChild from '@/components/DemoChild'
export default {
data(){
return {
name:'nihao'
}
},
components:{
DemoChild
}
}
子組件 DemoChild
<div id="demo_child">
<p @click="change"> DemoChild組件 {{nameFather}}</p>
</div>
export default {
//聲明model
model:{
prop:'nameFather', //這個prop的值就是自定義的props屬性,所以這里是'nameFather'
event:'modelChange' //model綁定的事件名内贮,自己隨意取
},
props:{
nameFather: String //自定義props屬性产园,nameFather
},
methods:{
change(){
//這里的第一個參數(shù)是model里的event,所以這里是'modelChange' 第二個參數(shù)是傳遞過去的值
this.$emit('modelChange','這是子組件傳遞過去的數(shù)據(jù)')
}
}
}