组件通信包括:子组件与父组件之间、兄弟组件之间、模块之间。
props是响应式的,可以做数据绑定
父组件引用子组件的时候利用v-bind去绑定message,传递给子组件(对应就是msg)
子组件要创建props选项,注册传递的msg值,就可以直接使用msg这个值了
父组件
<template>
<div>
<child :msg="message">child>
div>
template>
<script>
import child from './child.vue'
export default {
components: {
child
},
data () {
return {
message: 'father message';
}
}
}
script>
子组件
<template>
<div>{{msg}}div>
template>
<script>
export default {
props: {
msg: {
type: String,
default: true //默认值
}
}
}
script>
因为html对于大小写并不敏感,所以子组件中驼峰命名在父组件中建议采用下划线。传递给子组件的方法类似于一个回调函数。调用之后可以更改父组件中的内容,也算是子组件向父组件通信了。根据Vue风格指南中的建议,props的定义应该尽量详细,至少需要指定其类型。
子组件通过$emitc触发父组件的方法(通过@add-parent-total="addTotal"将add-parent-total和addTotal联系起来)
父组件
<template>
<child @add-parent-total="addTotal">child>
template>
<script>
import child from "./child.vue"
export default {
component {
child
},
data () {
return {
total: 0
}
},
methods: {
addTotal(args){
this.total++
console.log(args); //args就是传递值带的参数
}
}
}
script>
子组件
<template>
<button @click="addCounter">{{counter}}button>
template>
<script>
export default {
data () {
counter: 0
},
methods: {
addCounter(){
this.counter++
this.$emit('add-parent-total', args)
}
}
}
script>
父组件 --> 子组件
引用子组件并起名ref=“demo1”,然后通过this.$refs.demo1.getUser(elem)调用子组件中的getUser方法并传参(elem)
父组件 --> 子组件
方法一: 子组件直接用this. p a r e n t . x x x 这 样 直 接 调 用 父 组 件 的 方 法 方 法 二 : 引 用 子 组 件 并 用 v − o n 来 做 个 监 测 函 数 来 监 测 ; 子 组 件 通 过 t h i s . parent.xxx这样直接调用父组件的方法 方法二: 引用子组件并用v-on来做个监测函数来监测;子组件通过this. parent.xxx这样直接调用父组件的方法方法二:引用子组件并用v−on来做个监测函数来监测;子组件通过this.emit(‘方法名’,传递的参数)来调用父组件的方法
父组件
<template>
<son-demo ref="demo1" @sonname="son1">son-demo>
template>
<script>
import sonDemo from "./son-demo.vue"
export default {
data() {
return {
sondemoVal: 'test'
};
},
mounted() {
this.$ref.demo1.getUser(this.sondemoVal); // 父 --> 子的方法
},
methods: {
son1(temp) {
console.log('这里是父组件的方法son1: ${temp}');
}
}
}
script>
子组件
<template>
<div>{{msg}}div>
template>
<script>
export default {
methods: {
getUser(temp) {
console.log('sondemo--->' + temp);
}
},
mounted() {
this.$parent.son1('son'); // 子 --> 父的方法一;
this.$emit('sonname', 'son'); // 子 --> 父的方法二;
// ‘son’是要传递的参数
}
}
script>
eventBus
eventBus的原理是引入一个新的vue实例,通过分别调用这个实例的事件触发和监听来实现通信和参数传递。eventBus.js一般会直接用公共一个文件来存放vue实例。
import Vue from 'vue';
export default new Vue();
我们在apple.vue中监听一个事件
import eventBus from 'eventBus.js'
export default {
// 我们在create钩子中监听方法
create() {
console.log("this.getTarget是一个带参数的方法,但是这边只要将两者关联起来");
eventBus.$on('getTarget', this.getTarget);
},
beforeDestory() {
console.log("组件销毁前需要解绑事件。否则会出现重复触发事件的问题");
bus.$off('getTarget', this.getTarget);
},
methods: {
getTarget(param) {
// todo
}
}
}
在orange.vue中触发
// 必须引入同一个实例
import eventBus from 'eventBus.js'
export default {
methods: {
doSomething() {
eventBus.$emit("getTarget", 22);
console.log("向getTarget方法传参22")
}
}
}
vuex
待完善…
参考:
vue组件通信
vue组件间通信