Vue组件之间的两种常用通信方式
最近都一直学习Vue的知识,看了不少视频,之前完全不了解前端知识,所以还是遇到很多困难,
用惯了强类型语言来看js的代码真的有种感觉随笔写都不影响编译的感觉。
今天总结一下Vue中的组件传值问题。这里使用的demo直接vue init webpack-simple **** 命令初始化的。
父子组件通信
父组件传递给子组件多重类型
我们可以在props中做类型检测,下面看父子组件的代码。
父组件通过传值,子组件直接调用或者emit调用父组件的方法,父组件也可以直接拿到子组件的引用,直接使用子组件的值或者方法。
<template>
<div>
<h2>子组件</h2>
<input type="button" @click="log" value="click">
</div>
</template>
<script>
export default {
name: "Child",
data() {
return {
ownMsg: '子组件的msg'
}
},
methods: {
childLog() {
console.log('子组件Log')
},
log() {
console.log(this.passMsg)
console.log(this.obj)
//这是传过来的parent
this.parent.change()
//这是直接获取
this.$parent.change()
this.func1()
this.$emit('func2')
}
},
props: {
passMsg: {
type: String,
},
obj: {
type: Object,
},
parent: {
type: Object
},
func1: {
type: Function
}
}
}
</script>
<style scoped>
</style>
父组件
<template>
<div>
<h1>父组件</h1>
<h2> {
{
msg }}</h2>
<input type="button" @click="childFunc" value="click">
<Child
ref="child"
passMsg="msg"
:func1="change"
:obj="obj"
:parent="this"
@func2="change"
>
</Child>
</div>
</template>
<script>
import Child from "./Child";
export default {
name: "Parent",
data() {
return {
msg: "我是父组件的msg",
obj: {
name: "gg",
age: 15
}
}
},
methods: {
change() {
console.log('父组件log')
},
childFunc(){
const c = this.$refs.child
c.childLog()
console.log(c.ownMsg)
}
},
components: {
Child},
comments: {
Child
}
}
</script>
<style scoped>
</style>
非父子组件通信
非父子组件传值就有点类似于安卓中使用的EventBus了,我们首先准备一个event.js
import Vue from 'vue'
let VueEvent = new Vue()
export default VueEvent
新建一个兄弟组件,Brother.vue,这里点击按钮会发送内容到一个事件中去,如果有监听,就会触发对应的方法。
<template>
<div>
<h2>兄弟组件</h2>
<input type="input" value="click" v-model="ownMsg">
<input type="button" value="click" @click="send">
</div>
</template>
<script>
import VueEvent from "../model/event";
export default {
name: "Brother",
data() {
return {
ownMsg: '兄弟的msg'
}
},
methods: {
send() {
VueEvent.$emit('to_msg', this.ownMsg)
}
}
}
</script>
<style scoped>
</style>
再看看Child.vue
<template>
<div>
<h2>子组件</h2>
<input type="button" @click="log" value="click">
</div>
</template>
<script>
import VueEvent from "../model/event";
export default {
name: "Child",
data() {
return {
ownMsg: '子组件的msg'
}
},
methods: {
childLog() {
console.log('子组件Log')
},
log() {
console.log(this.passMsg)
console.log(this.obj)
//这是传过来的parent
this.parent.change()
//这是直接获取
this.$parent.change()
this.func1()
this.$emit('func2')
}
},
props: {
passMsg: {
type: String,
},
obj: {
type: Object,
},
parent: {
type: Object
},
func1: {
type: Function
}
},
mounted() {
VueEvent.$on('to_msg', function (data) {
console.log(data);
})
}
}
</script>
<style scoped>
</style>
最后这个方法就会打印对应日志,事件总线的形式。
这里简单介绍了两种,更详细的大家可以看看这个地址,基本罗列了各种方法。
Vue 组件通信方式全面详解
还没有评论,来说两句吧...