子传父
emit
当子组件需要向父组件传递数据,就要用到自定义事件
v-on 可以监听dom事件和 组件之间的自定义事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 父组件模板 -->
<div id="app">
<cpn @item-click = "cpnClick"></cpn>
</div>
<!-- 子组建模板 -->
<template id="cpn">
<div>
<button v-for="item in categories" @click="btnClick(item)">{{item.name}}</button>
</div>
</template>
<script src="./vue.js"></script>
<script>
// 子组件
const cpn = {
template :'#cpn',
data(){
return {
categories : [
{id: 'bbb', name : 'rementuij'},
{id: 'ccc', name : 'remtuij'},
{id: 'www', name : 'ij'},
{id: 'rrr', name : 'r日用j'},
{id: 'xxx', name : 't家电j'},
]
}
},
methods : {
btnClick(item){
// 发射事件 自定义事件
this.$emit('item-click')
}
}
}
// 父组件
const app = new Vue({
el: '#app',
data : {
message : 'www'
},
components : {
cpn
},
methods: {
cpnClick(){
console.log('cpnClick')
}
}
})
</script>
</body>
</html>