组件之间的传值之非父子(同级之间的传值用第三方量)

同级之间的传值1:
body部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<child></child>
<son></son>
</div>
js部分:
<script src="js/vue.js"></script>
<script>
var bus=new Vue()
Vue.component('child',{
template:<h1>这是child</h1> <button @click='sendMsg'>点击按钮传值</button>,
data:function(){
return{
msg:'这是非父子传值'
}
},
methods:{
sendMsg:function(){
bus.emit('send',this.msg) } } }) Vue.component('son',{ template:` <h1>这是son</h1> `, data:function(){ return{ mess:'' } }, mounted:function(){ bus.on('send',msg=>{
console.log(this);
this.mess=msg;
})
}
})

    new Vue({
        el:'#app'
    })
</script>

</body>
</html>

8.png

父子组件之间的传值案例:
body部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>父子组件传值</title>
</head>
<body>
<div id="app">
<chat-room></chat-room>
</div>
js部分:
<script src="js/vue.js"></script>
<script>
Vue.component('chat-room',{
template:<div> <ul> <li v-for="(value,index) in chatcont">{{value}}</li> </ul> <user @send='rcvMsg' userName='lhf'></user> <user @send='rcvMsg' userName='lbx'></user> </div>,
data:function(){
return{
chatcont:[]
}
},
methods:{
rcvMsg:function(txt){

                this.chatcont.push(txt)
            }
        }
    })
    
    Vue.component('user',{
        props:['userName'],
        template:`
            <div>
                <label>{{userName}}</label>
                <input type='text' v-model='msg'>
                <button @click='sendMsg'>点击发送</button>
            </div>
        `,
        data:function(){
            return{
                msg:''
            }
        },
        methods:{
            sendMsg:function(){
                this.$emit('send',this.userName+":"+this.msg)
            }
        }
    })
    new Vue({
        el:'#app'
    })
</script>

</body>
</html>


9.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容