一、子組件向父組件傳值
1、子向父?jìng)髦?需要用到自定義事件 $emit。
2、this.$emit('自定義的事件名')
3、當(dāng)自定義事件觸發(fā)時(shí),所綁定的函數(shù),就能自動(dòng)獲得這個(gè)事件在創(chuàng)建的時(shí)候 所寫(xiě)的參數(shù)
-
4、一般 子向父?jìng)髦担远x事件寫(xiě)在 子組件里面
image.png 5、然后在 父組件中 子標(biāo)簽上 觸發(fā)這個(gè)自定義屬性
6、當(dāng)觸發(fā)自定義事件(byval)時(shí),就能獲取到自定義事件上所攜帶的數(shù)據(jù)(this.cdata)
-
7、父組件中 子組件的標(biāo)簽上觸發(fā)事件,由于事件的觸發(fā) 必須綁定函數(shù)
image.png -
8、所以在父組件中我們需要定義一個(gè)接收數(shù)據(jù)的函數(shù),這個(gè)函數(shù) 可以自動(dòng)獲得 子組件中傳遞過(guò)來(lái)的參數(shù)(數(shù)據(jù))
image.png
二、父組件向子組件傳值
-
1、我們可以在子組件中的 props中定義變量
第一種寫(xiě)法有數(shù)據(jù)類(lèi)型,type寫(xiě)什么數(shù)據(jù)類(lèi)型,就能傳遞什么數(shù)據(jù)類(lèi)型
如果你定義的數(shù)據(jù)類(lèi)型不匹配,則會(huì)根據(jù)設(shè)置的數(shù)據(jù)類(lèi)型強(qiáng)制轉(zhuǎn)化

image.png
第二種寫(xiě)法 不規(guī)定數(shù)據(jù)類(lèi)型時(shí),按照下面的寫(xiě)法

image.png
-
2、然后在父組件內(nèi)使用 子組件props定義的變量傳值

image.png
-
3、子組件中可以直接將這個(gè)變量當(dāng)做數(shù)據(jù)來(lái)使用
三、最后子傳父、父?jìng)髯拥男Ч麍D

image.png
兩組件的代碼如下
子組件 Child.vue
<template>
<div id="child">
<h1>{{ msg }}</h1>
<button @click="sendData">子向父?jìng)髦?lt;/button>
<!-- 父組件中的數(shù)據(jù) -->
<h2>{{ abc }}</h2>
<h3>{{ aaa }}</h3>
</div>
</template>
<script>
export default {
name: 'Child',
data() {
return {
msg: '這是子組件',
cdata : '這是子組件中的數(shù)據(jù)',
}
},
props : {
abc : {
// 定義父組件傳遞過(guò)來(lái)的數(shù)據(jù)類(lèi)型
type : String,
requored : true,
// 如果你定義的數(shù)據(jù)類(lèi)型不匹配,則會(huì)根據(jù)設(shè)置的數(shù)據(jù)類(lèi)型強(qiáng)制轉(zhuǎn)化
}
},
// 不規(guī)定數(shù)據(jù)類(lèi)型時(shí),按照下面的寫(xiě)法
props: ["abc", 'aaa'],
methods: {
sendData() {
console.log(this);
// 子向父?jìng)髦?需要用到自定義事件 $emit
// this.$emit('自定義的事件名')
// 當(dāng)自定義事件觸發(fā)時(shí),所綁定的函數(shù),就能自動(dòng)獲得這個(gè)事件在創(chuàng)建的時(shí)候 所寫(xiě)的參數(shù)
this.$emit('byval',this.cdata);
}
}
}
</script>
<style lang="less" scoped>
#child {
padding: 10px;
border: 3px solid #007aff;
width: 90%;
height: 400px;
margin: auto;
}
</style>>
</style>
父組件 Father.vue
<template>
<div id="father">
<h1>{{ msg }}</h1>
<!-- 子組件中的數(shù)據(jù) -->
<h2>{{ data1 }}</h2>
<!-- 子組件 -->
<Child :abc="fdata" :aaa="aaa" @byval="getdata" />
</div>
</template>
<script>
// 引入子組件
import Child from '@/components/Child.vue';
export default {
name: 'Father',
data() {
return {
msg: '這是父組件',
fdata: '這是父組件里面的數(shù)據(jù)1',
aaa: '這是父組件里面的數(shù)據(jù)2',
data1: '',
}
},
components: {
Child,
},
methods: {
// 定義一個(gè)獲取子組件傳值的方法
getdata(datas) {
// datas 就是子向父?jìng)鬟^(guò)來(lái)的數(shù)據(jù)
// 由于函數(shù)內(nèi)的參數(shù) 不能直接用于渲染
// 所以我們需要在父組件的data中 定義一個(gè)變量
// 來(lái)接收一下 子組件傳遞過(guò)來(lái)的參數(shù)
this.data1 = datas;
}
}
}
</script>
<style lang="less" scoped>
</style>>
</style>


