一、非父子组件传值
只要不是父子组件,其他关系的组件都是非父子组件。
非父子组件传值方式:通过中间对象new Vue()
二、代码示例
代码中,在main.js设置中间对象,在App.vue引入One.vue和Two.vue
它们之间的传值关系:
One.vue传值给Two.vue
![](https://img-blog.csdnimg.cn/img_convert/dbbcc9cfc7acf2eec420141625158d52.png)
main.js
import Vue from 'vue'
import App from './App'
// 非父子组件传值:通过中间对象。
// 这个空实例有vue的所有功能,只是不能操作dom,生命周期走到created就结束了
Vue.prototype.$center = new Vue();
new Vue({
el: '#app',
render: h=>h(App)
})
App.vue
<template>
<div id="app">
one:<input type="checkbox" v-model="isShowOne"/>
two:<input type="checkbox" v-model="isShowTwo"/>
<hr/>
<One v-if="isShowOne"/>
<hr/>
<Two v-if="isShowTwo"/>
</div>
</template>
<script>
import One from './components/One'
import Two from './components/Two'
export default {
components: {
One,
Two
},
data(){
return {
isShowOne: true,
isShowTwo: true
}
}
}
</script>
<style>
</style>
One.vue
<template>
<div class="one">
<h1>one组件</h1>
<input type="text" ref="in"/>
<button @click="btnAction">发送</button>
</div>
</template>
<script>
export default {
methods: {
btnAction(){
let val = this.$refs.in.value;
// 触发事件
this.$center.$emit('send', val);
}
}
}
</script>
<style>
</style>
Two.vue
<template>
<div class="two">
<h1>two组件</h1>
<p>接收到的数据是:{{oneVal}}</p>
</div>
</template>
<script>
export default {
data(){
return {
oneVal: null
}
},
created(){
// 事件一定要满足先监听后触发的规则
this.$center.$on('send', (data)=>{
this.oneVal = data;
})
},
beforeDestroy(){
//移除监听
this.$center.$off('send');
}
}
</script>
<style>
</style>