<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vue实现非父子组件传值</title>
<script src="./lib/vue-2.4.0.js"></script>
</head>
<body>
<!-- coma的模板 -->
<template id="coma">
<div>
<h1>{{title}}</h1>
<button @click="sendMsg">发送</button>
</div>
</template>
<!-- comb的模板 -->
<template id="comb">
<div>
<h1>{{title}}</h1>
<h1>{{msg}}</h1>
</div>
</template>
<div id="app">
<!-- 调用coma组件 -->
<coma></coma>
<hr/>
<!-- 调用comb组件 -->
<comb></comb>
</div>
</body>
<script>
// 公共组件
var comm=new Vue();
// 组件a
Vue.component('coma',{
template:'#coma',
data:function(){
return {
title:'组件A',
msg:'传给兄弟组件的值'
}
},
methods:{
sendMsg:function(){
comm.$emit('myevent',this.msg)
}
},
created:function(){
// 注册自定义事件
comm.$emit('myevent',this.msg);
console.log('注册事件OK');
}
});
// 组件b
Vue.component('comb',{
template:'#comb',
data:function(){
return {
title:'组件B',
msg:''
}
},
mounted:function(){
comm.$on('myevent',(data)=>{
this.msg=data
});
}
});
var vm=new Vue({
el:'#app'
});
</script>
</html>
网友评论