vue组件之间的通讯

2017-09-21  本文已影响0人  a180754bf396

使用props传递数据,组件内部

<div id="app1">
<child my-message="组件内部数据传递"></child>
</div>
//js
<script>
Vue.component('child', {
props: ['myMessage'],
template: '<mark>{{ myMessage }}<mark/>'
});
new Vue({
el: '#app1'
})
</script>

父子之间传送数据

<div id="app2">
<input v-model="parentMsg">


<child :parent-msg="parentMsg"></child>
</div>
<script>
Vue.component('child', {
props: ['parentMsg'],
template: '<mark>{{ parentMsg }}<mark/>'
});
new Vue({
el: '#app2',
data: {
parentMsg: 'msg from parent!'
}
})
</script>

如果数据是引用对象则可以互传

props: ['initialCounter'],
data: function () {
return { counter: this.initialCounter }
}
//定义一个局部computed属性,此属性从 prop 的值计算得出
props: ['size'],
computed: {
normalizedSize: function () {
return this.size.trim().toLowerCase()
}
}

子子传数据

$emit $on

<div id="app3">
<p>Look at the parent's data: <mark>{{t}}</mark> & the child's data: <mark>{{childWords}}</mark></p>
<child v-on:add="pChange"></child>
<child v-on:add="pChange"></child>
<child v-on:click.native="native"></child>
</div>
<script>
Vue.component('child', {
template: <button @click="add">{{ c }}</button>,
data: function () {
return {
c: 0,
msg: 'I am from child's data'
}
},
methods: {
add: function () {
this.c += 1;
this.$emit('add',this.msg);
}
},
});
new Vue({
el: '#app3',
data: {
t: 0,
childWords: ''
},
methods: {
pChange: function (msg) {
this.t += 1;
this.childWords=msg;
},
native:function () {
alert('I am a native event ,which comes from the root element!');
}
}
})
</script>

<div id="app4">
<display></display>
<increment></increment>
</div>
<script>
var bus = new Vue();
Vue.component('increment', {
template: <button @click="add">+</button>,
data: function () {
return {count: 0}
},
methods: {
add: function () {
bus.$emit('inc', this.count+=1)
}
}
});
Vue.component('display', {
template: <span>Clicked: <mark>{{c}}</mark> times</span>,
data: function () {
return {c: 0}
},
created: function () {
var self=this;
// bus.$on('inc', function (num) {
// self.c = num
// });
bus.$on('inc', (num) =>
this.c = num
);
}
});
vm = new Vue({
el: "#app4",
})
</script>

上一篇下一篇

猜你喜欢

热点阅读