一润绵、子組件向父組件傳值
1版保、子向父傳值 需要用到自定義事件 $emit履植。
2付燥、this.$emit('自定義的事件名')
3、當(dāng)自定義事件觸發(fā)時啦膜,所綁定的函數(shù)晤斩,就能自動獲得這個事件在創(chuàng)建的時候 所寫的參數(shù)
-
4捏雌、一般 子向父傳值番挺,自定義事件寫在 子組件里面
image.png 5唠帝、然后在 父組件中 子標(biāo)簽上 觸發(fā)這個自定義屬性
6、當(dāng)觸發(fā)自定義事件(byval)時玄柏,就能獲取到自定義事件上所攜帶的數(shù)據(jù)(this.cdata)
-
7襟衰、父組件中 子組件的標(biāo)簽上觸發(fā)事件,由于事件的觸發(fā) 必須綁定函數(shù)
image.png -
8粪摘、所以在父組件中我們需要定義一個接收數(shù)據(jù)的函數(shù)瀑晒,這個函數(shù) 可以自動獲得 子組件中傳遞過來的參數(shù)(數(shù)據(jù))
image.png
二阀湿、父組件向子組件傳值
-
1、我們可以在子組件中的 props中定義變量
第一種寫法有數(shù)據(jù)類型瑰妄,type寫什么數(shù)據(jù)類型,就能傳遞什么數(shù)據(jù)類型
如果你定義的數(shù)據(jù)類型不匹配映砖,則會根據(jù)設(shè)置的數(shù)據(jù)類型強(qiáng)制轉(zhuǎn)化
image.png
第二種寫法 不規(guī)定數(shù)據(jù)類型時间坐,按照下面的寫法
image.png
-
2、然后在父組件內(nèi)使用 子組件props定義的變量傳值
image.png
-
3邑退、子組件中可以直接將這個變量當(dāng)做數(shù)據(jù)來使用
三竹宋、最后子傳父、父傳子的效果圖
image.png
兩組件的代碼如下
子組件 Child.vue
<template>
<div id="child">
<h1>{{ msg }}</h1>
<button @click="sendData">子向父傳值</button>
<!-- 父組件中的數(shù)據(jù) -->
<h2>{{ abc }}</h2>
<h3>{{ aaa }}</h3>
</div>
</template>
<script>
export default {
name: 'Child',
data() {
return {
msg: '這是子組件',
cdata : '這是子組件中的數(shù)據(jù)',
}
},
props : {
abc : {
// 定義父組件傳遞過來的數(shù)據(jù)類型
type : String,
requored : true,
// 如果你定義的數(shù)據(jù)類型不匹配地技,則會根據(jù)設(shè)置的數(shù)據(jù)類型強(qiáng)制轉(zhuǎn)化
}
},
// 不規(guī)定數(shù)據(jù)類型時蜈七,按照下面的寫法
props: ["abc", 'aaa'],
methods: {
sendData() {
console.log(this);
// 子向父傳值 需要用到自定義事件 $emit
// this.$emit('自定義的事件名')
// 當(dāng)自定義事件觸發(fā)時,所綁定的函數(shù)莫矗,就能自動獲得這個事件在創(chuàng)建的時候 所寫的參數(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: {
// 定義一個獲取子組件傳值的方法
getdata(datas) {
// datas 就是子向父傳過來的數(shù)據(jù)
// 由于函數(shù)內(nèi)的參數(shù) 不能直接用于渲染
// 所以我們需要在父組件的data中 定義一個變量
// 來接收一下 子組件傳遞過來的參數(shù)
this.data1 = datas;
}
}
}
</script>
<style lang="less" scoped>
</style>>
</style>