老师请讲一下思路,自己做的有点乱
来源:4-10 编程练习
慕函数4234673
2020-05-21 15:05:55
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
button {
padding: 10px 20px;
margin: 20px auto;
border-radius: 5px;
outline: none;
}
.red {
background: pink;
}
.green {
background: green;
}
</style>
</head>
<body>
<div id="app">
<item1></item1>
<item2></item2>
</div>
<script>
Vue.prototype.bus=new Vue()
Vue.component("item1",{
template:"<div><item3></item3></div>"
})
Vue.component("item2",{
template:"<button @click='btn2' :class='btn2'>组件二</button>",
data(){
return{
btn2:"green"
}
},
methods:{
btn2:function(){
this.bus.$emit("changetwo" ,this.btn2)
}
},
mounted:function(){
var self=this
this.bus.$on("changetwo",function(qq){
self.btn2=qq
})
}
})
Vue.component("item3",{
template:"<button @click='btn3' :class='btn3'>组件三</button>",
data(){
return{
btn3:"red"
}
}
})
var vm = new Vue({
el: "#app",
data:{
}
})
</script>
</body>
</html>
1回答
好帮手慕慕子
2020-05-21
同学你好,对于你的问题解答如下:
绑定事件名和类名不可以是同一个变量名。建议修改一下。
同学大体实现的思路是可以的。重点思路如下:
(1)在组件2的mounted中使用 this.bus.$on监听事件,设置组件2的样式。在组件3中使用this.bus.$emit给触发事件,传递类名。
(2)在组件3的mounted中使用 this.bus.$on监听事件,设置组件3的样式。在组件2中使用this.bus.$emit给触发事件,传递类名。


同学可以测试理解下,祝学习愉快~
相似问题