父组件给子组件传值
使用props,父组件可以使用props向子组件传递数据
父组件vue模板father. vue
<template>
<child :msg="message"></child>
</template>
<script>
import child from './child. vue';
export default {
components: {
child
},
data () {
return {
message: ' father message';
}
}
}
</script>
子组件vue模板child. vue:
<template>
<div>{{msg}}</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
required: true
}
}
}
</script>
子组件向父组件通信
父组件向子组件传递事件方法,子组件通过$emit触发事件,回调给父组件
父组件vue模板father. vue:
<template>
<child @msgFunc="func"></child>
</template>
<script>
import child from './child. vue';
export default {
components: {
child
},
methods: {
func (msg) {
console. log(msg);
}
}
}
</script>
子组件vue模板child. vue:
<template>
<button @click="handledick">点我</button>
</template>
<script>
export default {
props: {
msg: {
type: String,
required: true
}
},
methods () {
handledick () {
//
this. $emit('msgFunc');
)
}
}
</script>
非父子,兄弟组件之间通信
可以通过实例一个vue实例Bus作为媒介,要相互通信的兄弟组件之中,都引入Bus,然后通 过分别调用Bus事件触发和监听来实现通信和参数传递
Bus. js可以是这样:
import Vue from 'vue'
export default new Vue()
在需要通信的组件都引入Bus. js:
<template>
<button @click="toBus">子组件传给兄弟组件</button>
</template>
<script>
import Bus from '.. /common/js/bus. js'
export default{
methods: {
toBus () {
Bus.$emit ('on',来自兄弟组件')
}
}
}
</script>
另一个组件也import Bus. js在钩子函数中监听on事件
import Bus from '.. /common/js/bus. js'
export default {
data () {
return {
message: ' '
},
mounted () {
Bus.$on('on', (msg) => {
this.message = msg
})
}
}
Was this helpful?
0 / 0