老师,在本案例中我的代码执行结果是点击标签只改变了一次值之后就不变了

来源:4-9 非父子组件间的传值

慕斯卡7039390

2021-05-08 16:51:51

http://img.mukewang.com/climg/609650b50930f03c02470201.jpghttp://img.mukewang.com/climg/609650b50930f03c02470201.jpghttp://img.mukewang.com/climg/609650d5091f18e601170149.jpg

<!DOCTYPE html>

<html>

<head>

<title>非父子组件间的传值(Bus/总线/发布订阅模式/观察者模式)</title>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

</head>

<body>

<div id="root">

<child content="Dell"></child>

<child content="Lee"></child>

</div>

<script type="text/javascript">

Vue.prototype.bus=new Vue();

Vue.component('child',{

data:function(){

return {

selfContent:this.content

}

},

props:{

content:String

},

template:'<div @click="handleClick">{{selfContent}}</div>',

methods:{

handleClick:function(){

this.bus.$emit('change',this.selfContent);

}

},

mounted:function(){

var this_=this;

this.bus.$on('change',function(msg){

this_.selfContent=msg;

})

}

})

var vm=new Vue({

el:'#root'

})

</script>

</body>

</html>

http://img.mukewang.com/climg/60965109090d072801630171.jpg

写回答

1回答

好帮手慕久久

2021-05-08

同学你好,正确的效果就是改变一次,同学仔细看视频中的效果,老师在点击Lee和Dell之间,是刷新过页面的:

http://img.mukewang.com/climg/6096526609ba4fac05080219.jpg

只是刷新过程特别快,所以给同学造成了误解。

可以分析一下代码:

当点击Dell时,触发change事件,把“Dell”传出去,然后两个组件的内容都变成了“Dell”,这个时候,是没法点击“Lee”的(Lee已经没了),所以页面是刷新过的。

祝学习愉快!

0

0 学习 · 10739 问题

查看课程