一、$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