Props
這是最常用的一種方式。通過props選項,在父組件中傳遞數(shù)據(jù)給子組件。在子組件中使用props聲明該屬性,就可以訪問到父組件傳遞過來的數(shù)據(jù)了。
在父組件中:
<template>
<ChildComponent :message="hello"></ChildComponent>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
hello: 'Hello, Vue!'
}
}
}
</script>
在子組件中:
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: ['message']
}
</script>
emit
子組件向父組件傳遞數(shù)據(jù)的方式。在子組件中使用emit方法觸發(fā)一個自定義事件,并通過參數(shù)傳遞數(shù)據(jù)。在父組件中監(jiān)聽這個事件,就可以訪問到子組件傳遞過來的數(shù)據(jù)了。
首先,在子組件ChildComponent中定義一個customEvent事件:
<template>
<button @click="handleClick">傳遞數(shù)據(jù)</button>
</template>
<script>
export default {
methods: {
handleClick() {
const data = "Hello, World!"
this.$emit('customEvent', data);
}
}
}
</script>
上面代碼中,我們定義了一個點擊事件handleClick,當用戶點擊按鈕時,會觸發(fā)這個事件。在事件處理函數(shù)中,我們定義了一個字符串變量data,并通過this.$emit(‘customEvent’, data)方式把這個變量傳遞給父組件。
接下來,在父組件ParentComponent中通過v-on:或者簡寫成@來監(jiān)聽子組件發(fā)出的自定義事件:
<template>
<div>
<child-component @customEvent="handleCustomEvent"></child-component>
</div>
</template>
<script>
import ChildComponent from '@/components/ChildComponent.vue'
export default {
components: {
ChildComponent
},
methods: {
handleCustomEvent(data) {
console.log(data)
}
}
}
</script>
上面代碼中,我們使用@customEvent="handleCustomEvent"語法來監(jiān)聽子組件發(fā)出的自定義事件。在父組件的methods選項中,我們定義了handleCustomEvent方法,并接收子組件傳遞過來的數(shù)據(jù)。當子組件調(diào)用this.$emit(‘customEvent’, data)時,該方法會被觸發(fā),在控制臺輸出子組件傳遞過來的數(shù)據(jù)。
provide/inject
這種方式允許祖先組件向后代組件注入依賴,避免了props層層傳遞的麻煩。在祖先組件中使用provide選項提供一個變量或者方法,在后代組件中使用inject選項注入這個變量或者方法即可在后代組件中使用。
parent/$children屬性
可以直接訪問父組件或子組件中的數(shù)據(jù)或方法。但是,這種方式可能會使得組件難以維護和復用,不太建議使用。文章來源:http://www.zghlxwxcb.cn/news/detail-423781.html
總的來說,Props和emit是Vue中最常用的父子組件之間傳遞數(shù)據(jù)的方式。而provide/inject和parent/$children則是一些特殊場景下才會用到的方式文章來源地址http://www.zghlxwxcb.cn/news/detail-423781.html
到了這里,關于vue父子組件之間的傳參的幾種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!