vue父子組件傳值的原理是什么,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
文件目錄如下圖,example.vue是父組件,exampleChild.vue是子組件。

父組件引入子組件,父組件html的代碼如下:
<template>
<div>
<h4>這是父組件</h4>
<p >
<span>子組件傳過來的值是 “{{childValue}}”</span>
</p>
<example-child v-bind:message="parentMsg" @getChildValue="getValue"></example-child>
</div>
</template>
<script>
import exampleChild from './examplechild.vue';
export default {
name: "example.vue",
components: {
exampleChild
},
data(){
return {
parentMsg:'hello',
childValue:''
}
},
mounted(){
},
methods: {
getValue:function (val) {
this.childValue = val;
}
}
}
</script>
<style scoped>
</style>子組件代碼如下:
<template>
<div>
<p >我是子組件,父組件穿傳過來的值是{{message}}</p>
<p >
<button @click="send">點擊向父組件傳值</button>
</p>
</div>
</template>
<script>
export default {
name: "exampleChild.vue",
props:['message'],
data(){
return {
}
},
mounted(){
},
methods: {
send:function () {
this.$emit('getChildValue','你好父組件!')
}
}
}
</script>
<style scoped>
</style>1,父組件向子組件傳值。
在父組件中使用v-bind來綁定數據傳給子組件,如我寫的v-bind:message="parentMsg",把message字段傳給子組件,

在子組件中使用props接收值,如props:['message'],接收父組件傳過來的message字段,使用{{message}}就是可以使用父組件傳過來的值了。

2,子組件向父組件傳值。
子向父傳值需要一個“中轉站”,如我寫的getChildValue,命名隨便寫。
在子組件中使用$emit()來向父組件傳值。第一個參數就是這個“中轉站”,后面的參數是要傳的值,可以是多個。

在父組件中如下,也需要這個中轉站來接收值

getValue是接收子組件值的函數,參數val就是子組件傳過來的值,這樣就可以接收到子組件傳過來的值了。

看完上述內容,你們掌握vue父子組件傳值的原理是什么的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。