Vue非父子组件之间传值

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>非父子组件间的传值(bus/总线/发布订阅模式/观察者模式)</title>
        <script src="../js/vue.js"></script>
	</head>
	<body>
        <div id="root">
            <child content="Dell"></child>
            <child content="Lee"></child>
        </div>
	</body>
    <script>
        // 在每一个组件上添加BUS属性
        Vue.prototype.bus = new Vue()
        
        Vue.component('child',{
            props:{
              content:String  
            },
            data(){
                //子组件不能直接修改父组件的值
                return {
                    copyContent:this.content
                }
            },
            template:'
{{copyContent}}
'
, methods:{ handleClick(){ //通过bus向外触发事件 this.bus.$emit('change',this.copyContent) } }, mounted() { // 通过生命周期钩子监听bus触发的事件, // 每点击一次就会触发两次事件 是因为一共有两个组件每个组件上都绑定了一个bus ,mounted就触发两次 var this_ = this; this.bus.$on('change',function(msg){ this_.copyContent = msg; }) } }) var vm = new Vue({ el:'#root' }) </script> </html>

你可能感兴趣的:(vue)