vue 父子組件中的通信

父組件

<div><child @upup="change" :child-msg="data">

<div slot="slot1">父組件插入</div>

<child></div>

<div>{{childData}}</div>

export default {

components: {

child

},

data () {

return {

data: "from parent",

childData:""

}

},

methods:{

change(msg){

this.childData=msg;

this.data="parent change"

}

}

}

子組件

<li>{{msg}}</li>

<li><slot name="slot1">子組件<slot></li>

<li>{{childMsg}}<li>

<li><div@click="toParent">click To parent</div><li>

export default {

name:"child",

components: {

},

data () {

return {

msg: 'this is child',

data:"from child"

}

},

props:{

childMsg: {

type: String,

default: "null" //這樣可以指定默認的值

}

},

methods:{

toParent(){

this.$emit('upup',this.data); //主動觸發(fā)upup方法,'hehe'為向父組件傳遞的數(shù)據(jù)

}

}

}

子組件通過props來接收數(shù)據(jù):

name:"child",

components: {

},

data () {

return {

msg: 'this is child',

data:"from child"

}

},

props:{

childMsg: {

type: String,

default: "null" //這樣可以指定默認的值

}

},

methods:{

toParent(){

this.$emit('upup',this.data); //主動觸發(fā)upup方法,'hehe'為向父組件傳遞的數(shù)據(jù)

}

}

}

父組件向子組件傳值,子組件用props接受,data改變后,子組件內(nèi)childMsg也改變

子組件向父組件傳值,用事件,父組件接受事件要加在子組件上

順便用了slot當(dāng)子組件模板只有slot 時,父組件內(nèi)容片段將插入到 slot 所在的 DOM 位置,并替換掉 slot 標(biāo)簽本身。

點擊前


點擊后

查看上述代碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容