vue中怎么實現(xiàn)組件間參數(shù)傳遞,針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

舉例說明
例如:element-ui組件庫中使用switch開關(guān),有個屬性active-color是設(shè)置“打開時”的背景色。change事件是觸發(fā)狀態(tài)的事件。
<el-switch
v-model="value"
:active-color="activecolor"
@change="touchSwitch">
</el-switch>
<script>
export default {
data() {
return {
value: true,
activecolor: '#13ce66'
}
},
methods: {
touchSwitch () {
// 這里入方法
}
}
};
</script>分析代碼
我們分析上面的代碼
首先我們可以看到active-color是將特定的數(shù)據(jù)傳給組件,也就是父傳子組件。
其次是@change雖然監(jiān)聽的是改變事件,但是語法糖依然是$emit,什么emit我們在以后的文章中會講到,就是“拋出事件”。
這就分為組件的最基本功能:
?數(shù)據(jù)進(jìn)
?事件出
那組件的使用我們知道了,通過active-color傳入?yún)?shù),通過@來接收事件。
所以,我們來探究一下組件的內(nèi)部結(jié)構(gòu)是什么樣的?
我寫了一個小模型,是一個顯示標(biāo)題的小按鈕,通過div包裹。
<!-- type-box.vue -->
<template>
<div class="box" @click="ai_click(title)">{{title}}</div>
</template>
<script>
export default {
name: 'type-box',
props: {
title: {
type: String,
default: () => ''
}
},
methods: {
ai_click (title) {
this.$emit('ai_click', title)
}
}
}
</script>
<style scoped>
.box{
width: 250px;
height: 100px;
margin: 10px;
border-radius: 10px;
background-color: #3a8ee6;
color: white;
font-size: 25px;
line-height: 100px;
text-align: center;
cursor: pointer;
}
</style>使用方法:
<!-- 父組件使用 -->
<template>
<div>
<type-box title="演示盒子" @ai_click=“touch”></type-box>
</div>
</template>
<script>
import typeBox from './type-box'
export default {
components: {
typeBox
},
methods: {
touch (data) {
console.log(data)
}
}
}
</script>分析組件
接收
通過props接收父組件傳遞過來的數(shù)據(jù),通過工廠函數(shù)獲取一個默認(rèn)值。
傳遞
通過this.$emit('ai_click', title)告訴父組件,我要傳遞一個事件,名字叫“ai_click”,請通過@ai_click接收一下,并且我將title的值返回父組件。
關(guān)于vue中怎么實現(xiàn)組件間參數(shù)傳遞問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。
當(dāng)前題目:vue中怎么實現(xiàn)組件間參數(shù)傳遞-創(chuàng)新互聯(lián)
網(wǎng)頁地址:http://chinadenli.net/article30/dpphpo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計、域名注冊、微信公眾號、網(wǎng)站設(shè)計公司、App設(shè)計、自適應(yīng)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容