<!-- 父组件 -->
<template>
<child :msg='myMsg'></child>
</template>
<script>
import Child from "./components/Child"
export default {
components:{ Child },
data(){
return{
myMsg: 'hello child'
}
}
}
</script>
<!-- 子组件 -->
<template>
<div>{{ myMsg }}</div>
</template>
<script>
export default {
props: {
myMsg: { // hello child
type: String,
default: ''
}
}
}
</script>
<!-- 父组件 -->
<template>
<child @getMsg='updateMsg'></child>
</template>
<script>
import Child from "./components/Child"
export default {
components:{ Child },
methods: {
updateMsg: (val) => {
console.log(val) // hello parent
}
}
}
</script>
<!-- 子组件 -->
<template>
<button @click='onClick'>点击</button>
</template>
<script>
export default {
methods: {
onClick: () => {
this.$emit('getMsg', 'hello parent')
}
}
}
</script>
<!-- 父组件 -->
<template>
<child :msg.sync='myMsg'></child>
</template>
<script>
import Child from "./components/Child"
export default {
components:{ Child },
data(){
return{
myMsg: 'hello child'
}
}
}
</script>
<!-- 子组件 -->
<template>
<button @click='onClick'>点击</button>
</template>
<script>
export default {
methods: {
onClick: () => {
this.$emit('update:myMsg', 'hello parent')
}
}
}
</script>
// bus.js - 创建实例
import Vue from 'vue';
export default new Vue();
// 调用事件
import Bus from 'bus.js'
Bus.$emit('getTarget', 'hello world!');
// 注册事件
import Bus from 'bus.js'
Bus.$on('getTarget', target => {
console.log(target);
});
export default {
provide: {
name: 'hello'
}
}
// B.vue
export default {
inject: ['name'], // 通过this.name获取
mounted () {
console.log(this.name); // hello
}
}
2.6 $ref/$parent/$children