上文说到组件通信,父传子通过props
而子传父就要用到$emit,父组件监听子事件,父组件通过子组件 $event 访问到被抛出的这个值。
如下面的通过子组件点击分类,父组件获取子组件的点击
我是分割线
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
a {
text-align: right;
}
</style>
</head>
<body>
<template id="son">
<div>
<!--1.子组件监听点击事件-->
<button v-for="type in types" @click="typeClick(type)">{{ type.name }}</button>
</div>
</template>
<div id="app">
<!--2.父组件监听子事件,通过 $event 访问到被抛出的这个值-->
<son @type-click="sonClick"></son>
</div>
<hr>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
//父传子 props
//子传父 $emit 比如点击分类,告诉父组件,
//子传父
const son = {
template: '#son',
props:{
cmovies:Array,
cmessage: {
type:String,
default: 'aaaa',
}
},
data() {
return{
types:[
{id: 1, name: '热门推荐'},
{id: 2, name: '风景'},
{id: 3, name: '人物'},
{id: 4, name: '动漫'},
]
}
},
methods: {
//子点击事件:传给父组件
typeClick(type){
//发送事件,自定义事件,参数
this.$emit('type-click',type);
}
},
}
//父
let app = new Vue({
el: '#app',
data: {
message: '你好!',
movies:['《史莱姆》','《re:0》','《虫师》']
},
components: {
//增强写法 son:son,
son
},
methods: {
//父自定义事件
sonClick(type){
alert(type.name);
}
}
});
</script>
</body>
</html>
我是分割线
前台效果:
Title