vue非父子组件间的传值

<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <div id="app">
            <child content="dent"></child>
            <child content="lett"></child>
        </div>
    </body>
    <script>
    Vue.prototype.bus=new Vue()//给Vue绑定一个bus
    Vue.component('child',{
        data:function(){
            return {
                selfContent:this.content//把this.content的值返回给selfContent,给后面操作
            }
        },
        props:{
            content:String
        },
        template:'<div @click="handleClick">{{selfContent}}</div>',
        methods:{
            handleClick:function(){
                this.bus.$emit('change',this.selfContent)//触发事件用this.bus.$emit,传递参数this.content
            }
        },
        mounted:function(){//钩子
            var this_=this//当前对象,也就是为了改变当前对象的数据
            this.bus.$on('change',function(msg){//监听事件.msg是接收到传递的this.content

                this_.selfContent=msg//改变selfContent的数据

            })
        }
    })
        var app=new Vue({
            el:'#app',
            
        })
        
    </script>
</html>

标签: 无

发表评论:

whatsapp营销