題記
一直想總結(jié)這方面的知識,恰好上周又用到了,所以直接一次性總結(jié)了??
我的理解
對于兩個頁面?zhèn)髦?,我之前的理解一直停留在第一個頁面跳轉(zhuǎn)到第二個頁面,作為參數(shù)攜帶過去的某些值。后來涉及到兩個頁面互相傳值,就有點難受了,然后查了下,發(fā)現(xiàn)了父子、兄弟組件。其中的兄弟組件用的比較多。
父子組件傳值
父組件結(jié)構(gòu)樣例
<template>
<div>
<h1>父組件</h1>
<child></child>
</div>
</template>
<script>
import child from '@/components/child'
export default {
name: 'father',
components: {
child
},
data() {
return {
}
}
}
</script>
子組件結(jié)構(gòu)樣例
<template>
<div>
<h1>子組件</h1>
</div>
</template>
<script>
export default {
name: 'child',
data() {
return {
}
},
}
</script>
第一種情況:父組件給子組件傳值
關(guān)鍵:子組件通過
props獲取父組件傳來的值
父組件結(jié)構(gòu)
<template>
<div>
<h1>父組件</h1>
<child :sendMessage="fatherMessage"></child>
</div>
</template>
<script>
import child from '@/components/child'
export default {
name: 'father',
components: {
child
},
data() {
return {
fatherMessage: 'hello,my son' // 傳遞給子組件的值
}
}
}
</script>
子組件結(jié)構(gòu)
<template>
<div>
<h1>子組件</h1>
<span>獲取父組件的值:{{sendMessage}}</span>
</div>
</template>
<script>
export default {
name: 'child',
data() {
return {
}
},
props: ['sendMessage'] // 拿到父組件的值綁定到sendMessage,然后在子組件下顯示出來
}
</script>
第二種情況:子組件給父組件傳值
關(guān)鍵:
子組件通過觸發(fā)事件$emit給父組件傳值
父組件通過v-on:監(jiān)聽子組件的狀態(tài)
子組件結(jié)構(gòu)
<template>
<div>
<h1>子組件</h1>
<button @click="sendToFather">子組件給父組件傳值</button>
</div>
</template>
<script>
export default {
name: 'child',
data() {
return {
childMessage: 'hello,my father'
}
},
methods: {
sendToFather: function() {
// 參數(shù)1 getChildValue作為中間狀態(tài),參數(shù)2 this.childMsg即為傳遞給父組件的數(shù)據(jù)
this.$emit('getChildValue', this.childMessage);
}
}
}
</script>
父組件結(jié)構(gòu)
<template>
<div>
<h1>父組件</h1>
<!-- 引入子組件 定義一個on的方法監(jiān)聽子組件的狀態(tài),然后通過getChild方法獲取子組件傳遞的數(shù)據(jù)-->
<child v-on:getChildValue="getChild"></child>
<span>這是來自子組件的數(shù)據(jù):{{childValue}}</span>
</div>
</template>
<script>
import child from '@/components/child'
export default {
name: 'father',
components: {
child
},
data() {
return {
childValue: ''
}
},
methods: {
getChild: function(data) {
// 此時的參數(shù)data為子組件傳遞的值,即this.$emit()的第二個參數(shù)
this.childValue = data;
}
}
}
</script>
兄弟組件傳值
原理:這個也可以稱為同級組件之間的傳值。思路就是通過一個中間橋來進行傳值,它承擔(dān)起了組件之間通信的橋梁,也就是中央事件總線,推薦直接使用vuex進行狀態(tài)管理會比較方便。
關(guān)鍵:
第一個組件通過中間橋?qū)⑿畔⒈┞冻鋈?br> 第二個組件通過中間橋監(jiān)聽暴露事件,然后通過回調(diào)函數(shù)獲取信息
步驟
1.創(chuàng)建一個中間事件總線(在某個文件夾下面創(chuàng)建一個.js文件)
import Vue from 'vue'
export default new Vue()
2.第一個組件
<template>
<div>
<p>第一個組件</p>
<button @click="sendMsg">向第二個組件發(fā)送信息</button>
</div>
</template>
<script>
// 導(dǎo)入中間橋
import bridge from '../tools/center'
export default {
data () {
return {}
},
methods: {
sendMsg () {
bridge.$emit('firstMsg', 'hello,my partner')
}
}
}
</script>
3.第二個組件
<template>
<div>
<p>第二個組件</p>
<p>從同級組件傳遞過來的信息:{{message}}</p>
</div>
</template>
<script>
// 導(dǎo)入中間橋
import bridge from '../tools/center'
export default {
data () {
return {
message: '默認值'
}
},
mounted () {
let _this = this
bridge.$on('firstMsg', function (msg) {
_this.message = msg
})
}
}
</script>