记录一下vue组件间通信方式
父子组件通信
<template>
<div>
<h2>子组件部分</h2>
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
name: 'Child',
props: ['msg'],
data () {
return {
}
}
}
</script>
<style scoped>
</style>
<template>
<div id="app">
<child msg='hello'></child>
</div>
</template>
<script>
import child from '../components/Child'
export default {
name: 'Home',
components:{
child
},
data() {
return {
}
},
methods: {
}
}
</script>
子父组件通信
- 在子组件中创建一个按钮,给按钮绑定点击事件
- 使用$emit来触发一个自定义事件,并传递一个参数
<template>
<div>
<h2>子组件部分</h2>
<!-- 子组件向父组件传值或更新父组件值 -->
<button v-on:click="goParent">向父组件传值</button>
</div>
</template>
<script>
export default {
name: 'Child',
props: ['msg'],
data () {
return {
}
},
methods:{
goParent(){
this.$emit('goto','来自于子组件的值')
}
}
}
</script>
<template>
<div id="app">
<child msg='hello' v-on:goto='go'></child>
</div>
</template>
<script>
import child from '../components/Child'
export default {
name: 'Home',
components:{
child
},
data() {
return {
}
},
methods: {
go(data){
console.log(data);
}
}
}
</script>
兄弟组件通信
import Vue from 'Vue'
export default new Vue
<template>
<div>
<h2>第一个组件</h2>
<button v-on:click="sendMsg">向组件传值</button>
</div>
</template>
<script>
import bus from '../assets/js/eventBus'
export default {
name: 'firstChild',
data () {
return {
}
},
methods:{
sendMsg(){
bus.$emit('one','来自于第一个组件的值')
}
}
}
</script>
<style scoped>
</style>
<template>
<div>
<h2>第二个组件</h2>
<p>接受过来的参数:{{msg}}</p>
</div>
</template>
<script>
import bus from '../assets/js/eventBus'
export default {
name: 'secondChild',
data () {
return {
msg: 'mo'
}
},
mounted() {
var self = this
bus.$on('one',function(msg){
self.msg = msg
})
}
}
</script>
<style scoped>
</style>
<template>
<div id="app">
<firstChild></firstChild>
<secondChild></secondChild>
</div>
</template>
<script>
import firstChild from '../components/firstChild'
import secondChild from '../components/secondChild'
export default {
name: 'Main',
components:{
firstChild,
secondChild
}
}
</script>
<style>
</style>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。