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

先注冊父子各一個(gè)組件,代碼如下
<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)文章
vue iview的菜單組件Mune 點(diǎn)擊不高亮的解決方案
今天小編就為大家分享一篇vue iview的菜單組件Mune 點(diǎn)擊不高亮的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
vue3.0中給自己添加一個(gè)vue.config.js配置文件
這篇文章主要介紹了vue3.0中給自己添加一個(gè)vue.config.js配置文件方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
vue使用SVG實(shí)現(xiàn)圓形進(jìn)度條音樂播放
這篇文章主要為大家詳細(xì)介紹了vue使用SVG實(shí)現(xiàn)圓形進(jìn)度條音樂播放,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
vue項(xiàng)目中使用fetch的實(shí)現(xiàn)方法
這篇文章主要介紹了vue項(xiàng)目中使用fetch的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
Vue系列:通過vue-router如何傳遞參數(shù)示例
本篇文章主要介紹了Vue系列:通過vue-router如何傳遞參數(shù)示例,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01
Vue 項(xiàng)目遷移 React 路由部分經(jīng)驗(yàn)分享
這篇文章主要為大家介紹了Vue 項(xiàng)目遷移 React 路由部分經(jīng)驗(yàn)分享,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
vue使用JSON編輯器:vue-json-editor詳解
文章介紹了如何在Vue項(xiàng)目中使用JSON編輯器插件`vue-json-editor`,包括安裝、引入、注冊和使用示例,通過這些步驟,用戶可以在Vue應(yīng)用中輕松實(shí)現(xiàn)JSON數(shù)據(jù)的編輯功能,文章最后呼吁大家支持腳本之家2025-01-01

