一、$emit的用法
主要是子組件可以使用 $emit 觸發父組件的自定義事件。
子組件:通過自定義組件sendCity向父組件派發
<template>
<div>
<button @click="handleCity">changeCity</button>
</div>
</template>
<script>
export default {
name: 'Children',
data () {
return {
city: '杭州'
}
},
methods:{
handleCity(){
// 添加自定義事件,將“杭州”傳給父組件
this.$emit('sendCity', this.city)
}
}
}
</script>
父組件:
<template>
<div>
<div>{{toCity}}</div>
<Children @sendCity="sendCity"/>
</div>
</template>
<script>
import Children from './Children'
export default {
name: 'father',
data () {
return {
toCity: '上海'
}
},
components:{
Children
},
methods:{
sendCity(city){// city爲$emit的第二個參數
this.toCity = city
}
}
}
</script>
============》
二、props的用法
父組件可以使用 props 把數據傳給子組件。
子組件props常用寫法三連拍:
方式一:以字符串數組形式列出的 prop
props: ['title', 'likes', 'isPublished', 'commentIds', 'author']
方式二:帶有默認值的數字
props: { list: { type: Number, default: 100 }, }
方式三:
props{ propE: { type: Object, // 對象或數組默認值必須從一個工廠函數獲取 default: function () { // 默認值 return { message: 'hello' } } }, propF: { type: Array, // 對象或數組默認值必須從一個工廠函數獲取 default: function () { return [] } } }
子組件:
<template>
<div>
<div v-for="(item, index) in list" :key="index">
{{item}}
</div>
</div>
</template>
<script>
export default {
name: 'Children',
props:{
list: {
type: Array
}
},
data () {
return {
city: '杭州',
}
}
}
</script>
父組件:
<template>
<div>
<Children :list="list"/>
</div>
</template>
<script>
import Children from './Children'
export default {
name: 'father',
data () {
return {
list: ["時間", "金錢", "生命", "健康"]
}
},
components:{
Children
}
}
</script>
三、非父子組件通信
這種方式是非父子組件最方便的一種方式了。可以解決簡單的通信問題,而不用去麻煩Vuex了。
首先在main.js 給Vue原型上添加屬性。如下所示。
Vue.prototype.bus = new Vue()
假設現在有兩個組件,組件Input和組件List,它們互爲兄弟組件。組件Input向組件List發送數據。
Input組件:
<button @click="addTitle">add</button>
data () {
return {
title: '時間'
}
},
methods: {
addTitle(){
// 調用自定義組件,實現兄弟組件通信
this.bus.$emit('onAddTitle', this.title)
}
}
List組件:
mounted(){
// 綁定自定義組件
// 用函數的名字是爲了解綁一個事件
this.bus.$on('onAddTitle', function(title){
console.log('on add title', title)
})
},
beforeDestroy(){
// 及時銷燬自定義組件,防止造成內存泄漏
this.bus.$off('onAddTitle', function(title){
console.log('on add title', title)
})
}
List組件在mounted的鉤子上調用,然後通過beforeDestory進行銷燬,防止數據量過大。
如果想用vuex參考我的另外篇文章:https://blog.csdn.net/qq_38588845/article/details/104186339