一. 父子组件传值
1.props/$emit
Parent.vue
<template>
<div>
<h1>Parent</h1>
<h3>{{msg}}</h3>
<m-child :msg="'from Parent Msg'" @showMsg="getMsg"></m-child>
</div>
</template>
<script>
import MChild from './Child'
export default {
data() {
return {
msg: ''
}
},
components: {
MChild,
},
methods: {
getMsg(val) {
this.msg = val
}
},
}
</script>
child.vue
<template>
<div>
<h3>Child</h3>
<h3>{{ msg }}</h3>
<button @click="sendMsg">点我</button>
</div>
</template>
<script>
export default {
props: {
msg: {
type: String,
default: ''
},
},
methods: {
sendMsg() {
this.$emit('showMsg','I am from Child')
}
},
}
</script>
<style scoped>
</style>
2.this.$children / this.$parent
在父组件 Parent.vue 中调用子组件的data
mouted() {
console.log(this.$children[0].msg)
}
注:msg 是子组件中 data 定义的属性名
子组件调用父组件过程一样
3.this.$refs
在父组件中定义子组件的ref属性
<m-child :msg="'from Parent Msg'" @showMsg="getMsg" ref="child"></m-child>
后调用
mounted () {
// 调用 this.$children 传值
console.log(this.$children[0])
// 调用 this.$refs 与 上面 this.$children 等价
console.log(this.$refs.child)
},
二. 非父子组件中传值
1.事件总线
// 原理上是创建一个公共的js文件,专门用来传递信息
//1.创建bus.js
import Vue from 'vue'
// 非父子组件交互的公共js文件
export default new Vue;
// 在需要传递的地方引入
import bus from './util/bus'
// 传递信息
bus.$emit('msg',val)
//接受信息
bus.$emit('msg', val=>{
console.log(val)
})