Vue父子之間值傳遞的實例教程
將通過兩個input框?qū)崿F(xiàn)父子之間的值傳遞作為演示,效果圖

先注冊父子各一個組件,代碼如下
<div id="app">
<parent></parent>
</div>
<template id="parent">
<div>
<input type="text" v-model="text" placeholder="parent">
<son></son>
</div>
</template>
<template id="son">
<div>
<input type="text" placeholder="son">
</div>
</template>
new Vue({
el: "#app",
components: {
parent: {
template: '#parent',
data() {
return {
text: ''
}
},
components: {
son: {
template: '#son'
}
}
}
}
})

一、父傳子
再父組件通過屬性傳遞值
<template id="parent">
<div>
<input type="text" v-model="text" placeholder="parent">
<son :text="text"></son>//通過屬性值傳遞
</div>
</template>
子組件通過props屬性接受
components: {
son: {
template: '#son',
props:['text'] //通過props屬性接受父傳遞過來的值
}
}
這樣我們就可以使用父組件傳遞過來的值了
<template id="son">
<div>
<input type="text" placeholder="son" :value="text">//使用父元素傳遞過來的值
</div>
</template>
看下現(xiàn)在的效果

父組件向子組件傳遞成功
二、子傳父
通過父組件自定義事件,然后子組件用$emit(event,aguments)調(diào)用
<template id="parent">
<div>
<input type="text" v-model="text" placeholder="parent">
<son :text="text" @ev="item"></son>//自定義事件
</div>
</template>
components: {
parent: {
template: '#parent',
data() {
return {
text: ''
}
},
components: {
son: {
template: '#son',
props: ['text']
}
},
methods: {
item(v) { //自定義事件觸發(fā)的方法
this.text = v //使用子組件傳遞過來的值改變this.text數(shù)據(jù)
}
}
}
}
再子組件觸發(fā)自定義事件
<template id="son">
<div>
<input type="text" placeholder="son" :value="text" @input="emit" ref="son">//觸發(fā)自定義事件
</div>
</template>
components: {
parent: {
template: '#parent',
data() {
return {
text: ''
}
},
components: {
son: {
template: '#son',
props: ['text'],
methods: {
emit() {
this.$emit('ev', this.$refs.son.value) //觸發(fā)自定義事件,并傳遞值
}
}
}
},
methods: {
item(v) {
this.text = v
}
}
}
}
這樣就完成了子傳父,父傳子,效果也完成了
總結(jié)
到此這篇關(guān)于Vue父子之間值傳遞的文章就介紹到這了,更多相關(guān)Vue父子值傳遞內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3.0中給自己添加一個vue.config.js配置文件
這篇文章主要介紹了vue3.0中給自己添加一個vue.config.js配置文件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
vue使用SVG實現(xiàn)圓形進(jìn)度條音樂播放
這篇文章主要為大家詳細(xì)介紹了vue使用SVG實現(xiàn)圓形進(jìn)度條音樂播放,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
Vue系列:通過vue-router如何傳遞參數(shù)示例
本篇文章主要介紹了Vue系列:通過vue-router如何傳遞參數(shù)示例,具有一定的參考價值,有興趣的可以了解一下。2017-01-01
vue使用JSON編輯器:vue-json-editor詳解
文章介紹了如何在Vue項目中使用JSON編輯器插件`vue-json-editor`,包括安裝、引入、注冊和使用示例,通過這些步驟,用戶可以在Vue應(yīng)用中輕松實現(xiàn)JSON數(shù)據(jù)的編輯功能,文章最后呼吁大家支持腳本之家2025-01-01

