1、父子组件通信
<template id="father">
<div>
father
<Son :qian = "money"></Son>
</div>
</template>
<template id="son">
<div>
son
<p> 老爸给了我 {{ money }} 生活费 </p>
</div>
</template>
</body>
<script src="../../lib/vue.js"></script>
<script>
Vue.component('Father',{
template: '#father',
data () {
return {
money: 2000
}
}
})
Vue.component('Son',{
template: '#son',
props: ['qian']
})
new Vue({
el: '#app'
})
2、子父组件通信
<div id="app">
<Father></Father>
</div>
<template id="father">
<div>
<h3> 这里是父组件 </h3>
<p> 我现在有: {{ xiaojinku }} </p>
<!-- 这个的@后的事件名称可以任意 @后的就是自定义事件, =后的就是事件处理程序 -->
<Son @get = "get"></Son>
</div>
</template>
<template id="son">
<div>
<h4> 这里是Son 组件</h4>
<button @click = "give"> 给红包 </button>
</div>
</template>
</body>
<script src="../../lib/vue.js"></script>
<script>
Vue.component('Father',{
data () {
return {
xiaojinku: 0
}
},
template: '#father',
methods: {
get ( val ) {
this.xiaojinku = val
}
}
})
Vue.component('Son',{
template: '#son',
data () {
return {
hongbao: 1000
}
},
methods: {
give () {
this.$emit('get',this.hongbao)
}
}
})
var vm = new Vue({
el: '#app'
})
3、非父子组件通信-ref
<div id="app">
<Father></Father>
</div>
<template id="father">
<div>
<Son ref='son'></son>
<hr>
<Daughter :kick='kick'></Daughter>
</div>
</template>
<template id="son">
<div>
<p v-if='flag'>哭哭哭哭哭哭哭哭哭哭哭</p>
</div>
</template>
<template id="daughter">
<div>
<button @click='kick'>打</button>
</div>
</template>
</body>
<script src="../lib/vue.js"></script>
<script>
Vue.component("Father",{
template:'#father',
methods:{
kick(){
this.$refs.son.change()
}
}
})
Vue.component("Son",{
template:'#son',
data(){
return{
flag:false
}
},
methods:{
change(){
this.flag=true
}
}
})
Vue.component("Daughter",{
template:'#daughter',
props:['kick']
})
new Vue({
el:'#app'
})
4、非父子组件通信-bus
<div id="app">
<my-title></my-title>
<my-content></my-content>
</div>
<template id="title">
<div>
<input type="text" v-model = "val" @keyup.enter = "addTodos">
</div>
</template>
<template id="content">
<div>
<ul>
<li v-for = "todo in todos" :key = "todo.id">
{{ todo.task }}
</li>
</ul>
</div>
</template>
</body>
<script src="../../lib/vue.js"></script>
<script>
var bus = new Vue()
Vue.component('MyTitle',{
template: '#title',
data () {
return {
val: ''
}
},
methods: {
addTodos () {
bus.$emit('add', this.val )
}
}
})
Vue.component('MyContent',{
template: '#content',
data () {
return {
todos: [
{
id: 1,
task: '任务一'
},
{
id: 2,
task: '任务二'
}
]
}
},
mounted () {
var _this = this
bus.$on('add',function ( val ) {
_this.todos.push({
id: _this.todos.length + 1,
task: val
})
})
}
})
new Vue({
el: '#app'
})