1、父子通信
//在html中的相关代码
<body>
<div id="app">
<alert change_alert="再见"></alert> //如果我们想要点击按钮的时候弹出的内容时change_alert中的“再见”的话,那么我们要在vue.js中进行相关的操作
</div>
</body>
//在vue.js中的相关代码
Vue.component('alert',{ //定义了一个<alert>组件
template:'<button @click="on_click">点击我</button>',
porps:['change_alert'], //Vue中给我提供这样的方法porps
methods:{
on_click:function(){
alert(this.change_alert);
},
}
});
var app = new Vue({ //作用域,没有作用域我们定义的组件也无法显示
el:'#app',
});
————————我是分隔符————————
//在html中的相关代码
<body>
<div id="app">
<username username = "张三三"></username>
</div>
</body>
//在vue.js中的相关代码
Vue.component('username',{ //定义了一个<alert>组件
template:'<a :herf="\'http=user/\'+username" @click="on_click">@{{username}}</a>', //这里我们给a标记动态传入username,只要修改html中的username就可以,在给a标记添加herf的时候要注意地址中单双引号的使用,这里就使用了转义字符。
porps:['username'], //Vue中给我提供这样的方法porps
methods:{
on_click:function(){
alert(this.username);
},
}
});
var app = new Vue({ //作用域,没有作用域我们定义的组件也无法显示
el:'#app',
});
子父通信
//在html中的相关代码
<body>
<div id="app">
<balance></balance>
</div>
</body>
//在vue.js中的相关代码
Vue.component('balance',{
template:`
<div>
<show @show-balance="show_balance = true"></show>
<div v-if="show_balance">YES!</div>
</div>`,
data:function(){
return{
show_balance: false,
}
},
});
Vue.component('show',{
template:'<button @click="on_click()">你喜欢WEB前端么?</button>',
methods:{
on_click:function(){
return this.$emit('show-balance',{a:1,b:2});
}
}
});
var app = new Vue({
el:'#app',
});
如果想要传入参数,可以做一下修改。
Vue.component('balance',{
template:`
<div>
<show @show-balance="show_balance"></show>
<div v-if="show">YES!</div>
</div>`,
methods:{
show_balance:function(data){
this.show = true;
console.log('data',data);
}
},
data:function(){
return{
show: false,
}
},
});
Vue.component('show',{
template:'<button @click="on_click()">你喜欢WEB前端么?</button>',
methods:{
on_click:function(){
return this.$emit('show-balance',{a:1,b:2});
}
}
});
var app = new Vue({
el:'#app',
});
任意及平行组件间通信
//在html中的相关代码
<div id="app">
<mumu></mumu>
<haha></haha>
</div>
var Event = new Vue();
Vue.component('mumu',{
template:'<div>木木说:<input @keyup="on_change" type="text" v-model="i_said">{{i_said}}</div>',
data:function () {
return{
i_said:'',
}
},
methods:{
on_change:function () {
return Event.$emit('mumu-said-something',this.i_said);
}
},
});
Vue.component('niqiyao',{
template:'<div>哈哈听到木木说:{{mumu_said}}</div>',
data:function () {
return{
mumu_said:'',
}
},
mounted:function(){
var me = this;
Event.$on('mumu-said-something',function (data) {
me.mumu_said = data;
});
},
});
var app = new Vue({
el:'#app',
});