1. 组件间的通信
父子间的通信
通过props
父组件:
1.在父组件引入子组件
- 在components:{ } 里声明子组件
- 给子组件传值
子组件:
1.在props:[] 里声明传参的参数名,如:props:['a']
2.使用传过来的值,如:{{a}}
兄弟间的通信
用一个空的 Vue 实例作为中央事件总线:
1.新建一个bus.js,里面注册一个新的vue实例,如下:
import Vue from 'vue'
export var bus = new Vue()
- 在要通信的子组件中引入bus.js,在通信的组件里定义bus.$emit(' 名字1', '传值'),
3.在被通信的组件的created里定义:bus.$on('名字1', (text) => {
console.log(text)
})
Child1.vue
<template id='c1'>
<button @click="alertMsg">{{txt11}}</button>
</template>
<script>
import {bus} from '../utils/bus.js'
export default {
name: 'child1',
// template: '#c1',
props: ['txt11'],
data(){
return {
}
},
methods: {
alertMsg(){
alert(1)
bus.$emit('tip', '123')
}
}
}
</script>
<style>
</style>
Child2.vue
<template id='c2'>
<button @click="alertMsg">{{txt22}}</button>
</template>
<script>
import {bus} from '../utils/bus.js'
export default {
name: 'child2',
// template: '#c2',
props: ['txt22'],
data(){
return {
}
},
created () {
bus.$on('tip', (text) => {
console.log(text)
})
},
methods: {
alertMsg() {
alert(2)
}
}
}
</script>
<style>
</style>
Parent.vue
<template id='p'>
<div>
<child1 :txt11 = txt1></child1>
<child2 :txt22 = txt2></child2>
</div>
</template>
<script>
import child1 from './Child1'
import child2 from './Child2'
export default {
name: 'parent',
// template: '#p',
data() {
return {
txt1: '孩子1',
txt2: '孩子2'
}
},
components: {
// 'child1': child1,
// 'child2': child2,
child1,
child2
}
}
</script>
<style>
</style>
网友评论