1.event bus事件总栈
首先在创建个utils文件夹,在里面创建个index.js文件,文件内容如下:
// event bus
import Vue from 'vue';
// 首先创建一个实例
const bus = new Vue();
export default bus;
然后在创建组件b与组件a
<template>
<div>
<div>我是B,下面是由A传过来的值</div>
<div>{{ msg}}</div>
</div>
</template>
<script>
import bus from '@/utils/index.js'
export default {
data() {
return {
msg: ''
}
},
created() {
bus.$on('sendMessage',(msg) => {
console.log(msg)
this.msg = msg
})
}
}
</script>
<template>
<div>
<div>我是A</div>
<input type="text" v-model="msg"/>
<button @click="sendMeaage">发送消息</button>
</div>
</template>
<script>
import bus from '@/utils/index.js'
export default {
data() {
return {
msg: ''
}
},
methods: {
sendMeaage() {
bus.$emit('sendMessage', this.msg)
}
}
}
</script>
<template>
<div id="app">
<A></A>
<B></B>
</div>
</template>
<script>
import A from './view/A.vue';
import B from './view/b.vue'
export default {
name: 'App',
components: {
A,
B
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
2.prvide与inject(跨级层共享数据)
1.父组件 privde提供数据
<template>
<div id="app">
<div>我是App</div>
<input type="text" v-model="sendMessages"/>
<button @click="sendMeaage">发送消息</button>
<A></A>
<B></B>
</div>
</template>
<script>
import A from './view/A.vue';
import B from './view/b.vue'
export default {
data() {
return {
sendMessages: '',
msgObj: {
msg: '我是基础信息'
}
}
},
provide() {
return {
color: 'jjj', //非响应式
// 响应式
msgObj: this.msgObj
}
},
name: 'App',
components: {
A,
B
},
methods: {
sendMeaage() {
// console.log(this.msgObj.msg)
// console.log(this.msg, this.msgObj.msg)
this.msgObj.msg = this.sendMessages
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
-子组件
<template>
<div>
<div>我是B,下面是由A传过来的值</div>
<div>{{ msgObj.msg }}</div>
</div>
</template>
<script>
// import bus from '@/utils/index.js'
export default {
inject: ['msgObj'],
created() {
console.log(this.msgObj)
}
}
</script>