vue父子組件之間的傳參的幾種方式小結(jié)
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,當(dāng)用戶點擊按鈕時,會觸發(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ù)。當(dāng)子組件調(diào)用this.$emit(‘customEvent’, data)時,該方法會被觸發(fā),在控制臺輸出子組件傳遞過來的數(shù)據(jù)。
provide/inject
這種方式允許祖先組件向后代組件注入依賴,避免了props層層傳遞的麻煩。在祖先組件中使用provide選項提供一個變量或者方法,在后代組件中使用inject選項注入這個變量或者方法即可在后代組件中使用。
parent/$children屬性
可以直接訪問父組件或子組件中的數(shù)據(jù)或方法。但是,這種方式可能會使得組件難以維護(hù)和復(fù)用,不太建議使用。
總的來說,Props和emit是Vue中最常用的父子組件之間傳遞數(shù)據(jù)的方式。而provide/inject和parent/$children則是一些特殊場景下才會用到的方式
到此這篇關(guān)于vue父子組件之間的傳參的幾種方式小結(jié)的文章就介紹到這了,更多相關(guān)vue父子組件傳參內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue中g(shù)et方法\post方法如何傳遞數(shù)組參數(shù)詳解
在前后端交互的時候,有時候需要通過get或者delete傳遞一個數(shù)組給后臺,下面下面這篇文章主要給大家介紹了關(guān)于vue中g(shù)et方法\post方法如何傳遞數(shù)組參數(shù),文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03
深入理解Vue-cli搭建項目后的目錄結(jié)構(gòu)探秘
本篇文章主要介紹了深入理解Vue-cli搭建項目后的目錄結(jié)構(gòu)探秘,具有一定的參考價值,有興趣的可以了解一下2017-07-07
vue前端el-input輸入限制輸入位數(shù)及輸入規(guī)則
這篇文章主要給大家介紹了關(guān)于vue前端el-input輸入限制輸入位數(shù)及輸入規(guī)則的相關(guān)資料,文中通過代碼介紹的介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用vue具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09
Vue+Webpack完美整合富文本編輯器TinyMce的方法
這篇文章主要介紹了Vue+Webpack完美整合富文本編輯器TinyMce的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
Vue2?this?能夠直接獲取到?data?和?methods?的原理分析
這篇文章主要介紹了Vue2?this能夠直接獲取到data和methods的原理分析,因為methods里的方法通過bind指定了this為new?Vue的實例2022-06-06

