一个问题 麻烦老师看下
来源:4-10 编程练习
喝牛奶对身体好
2020-09-19 12:26:09
bus是不是最好只在不同的子组件中传递数据,能不能在复用组件的时候使用bus传递不同数据呢?
比如这个编程练习,只注册一个子组件 ,给子组件传值的时候传不同的值就可以达到复用实现两个按钮的不同效果,但是如果相互之间发起通信,bus会触发两次,就像老师讲的那样两个组件的值都会同时变化 ,bus能避免或者解决这个问题吗
1回答
同学你好,问题解答如下:
1.bus的确最好是用在两个不相干的组件之间传递数据比较好,当然也可以用在同一组件之间传递数据,比如视频中老师举得例子,同学可以再看一下。
2.bus用在复用组件之间传值,事件会触发两次,这个问题,我们可以如下这样处理一下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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;
}
</style>
</head>
<body>
<div id="app">
<!-- 给同一个组件 绑定不同的index,区分一下 -->
<com-po2 :index=1></com-po2>
<com-po2 :index=2></com-po2>
</div>
<script>
// 在此补充代码
Vue.prototype.bus = new Vue();
Vue.component("com-po2",{
template:'<button :class="styleArr" @click="changeCls">组件</button>',
data:function(){
return {
styleArr:""
}
},
props:{
index:Number
},
methods:{
//click事件 处理函数
changeCls:function(){
//根据当前 点击的哪个 组件 来触发不同的事件
if(this.index==1){
this.bus.$emit("changeClass1") //点击第一个组件触发的事件
}else{
this.bus.$emit("changeClass2") //点击第二个组件触发的事件
}
}
},
mounted:function(){
if(this.index==1){ //第一个组件 需要监听 第二个组件触发的事件
this.bus.$on("changeClass2",() => {
console.log(this.index); //打印一下 当前组件 是哪个
console.log("组件1 监听到了 组件2 触发的事件");
})
}else{
this.bus.$on("changeClass1",() => {
console.log(this.index);
console.log("组件2 监听 到了组件1 触发的事件");
})
}
}
})
var vm = new Vue({
el: "#app",
data:{}
})
</script>
</body>
</html>3. 4-10的编程练习,可以使用同一个组件实现,但是逻辑稍微有点复杂,老师给同学提供一个方案,同学可以扩展一下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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;
}
.pink {
background: pink;
}
.green {
background: green;
}
</style>
</head>
<body>
<div id="app">
<!-- 给同一个组件 绑定不同的index,区分一下 -->
<com-po2 :index=1></com-po2>
<com-po2 :index=2></com-po2>
</div>
<script>
// 在此补充代码
Vue.prototype.bus = new Vue();
Vue.component("com-po2",{
template:'<button :class="styleArr" @click="changeCls">组件2</button>',
data:function(){
return {
styleArr:""
}
},
props:{
index:Number
},
methods:{
//click事件 处理函数
changeCls:function(){
//点击不同的组件 触发同一个事件 传递不同的数据
if(this.index==1){
this.bus.$emit("changeClass",{
index:1, //标记是谁触发的
class:"pink" //将另一个组件的类名 改成什么
})
}else{
this.bus.$emit("changeClass",{
index:2,
class:"green"
})
}
}
},
mounted:function(){
//初始时,根据组件的index值,为两个组件设置不同的样式
if(this.index==1){
this.styleArr=""
}else{
this.styleArr="green"
}
this.bus.$on("changeClass",(cls) => { //监听事件
if(this.index!=cls.index){ //触发事件的组件 不是当前的组件 就改变当前组件的类名
this.styleArr=cls.class
}
})
}
})
var vm = new Vue({
el: "#app",
data:{}
})
</script>
</body>
</html>上述代码,同学可以作为扩展看一下,如果理解不了,可以先放放,等熟悉了知识点,再回头看。
如果我的回答帮到了你,欢迎采纳,祝学习愉快!
相似问题