$emit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>
<body>
<div id="demo">
{{total}}
<!-- 自定义组件进行传递数据 -->
<child-assemly @change='handleCount'></child-assemly>
</div>
<script>
Vue.component('child-assemly',{
template:'<div>\
<button @click="handleadd">+1000 //子组件中定义了点击事件 事件定义在子组件的methods中</button>\
<button @click="handleminus">-1000 //子组件中定义了点击事件</button>\
</div>',
data:function(){
return{
count:1000
}
},
methods:{
//template中DOM中的计算方法进行定义
handleadd:function(){
this.count=this.count+1000
//$emit('事件名',传递的数据,可以传递多个参数) change就是父组件中DOM中的change 名字随便写
this.$emit('change',this.count)
},
handleminus:function(){
this.count=this.count-1000
this.$emit('change',this.count)
}
}
})
var app = new Vue({
el: '#demo',
data:{
total:1000
},
methods:{
//自定义组件 value 就是子组件中传递出来的数据 this.count
handleCount:function(value){
this.total=value
}
}
})
</script>
</body>
</html>
复制代码
转载于:https://juejin.im/post/5ba0d15ee51d451a3f4bf71f