如何在子组件中监听全局变量—使用vuex

背景描述:

我们有两个独立的组件,组件A,组件B。两个组件都有下拉框,我们的目标就是点击A时出现下拉框,然后点击B时,A的下拉框会自动收回,只留下B的下拉框。

步骤一:

在main.js中引入vuex:

import Vue from 'vue'
import Vuex from 'vuex';

Vue.use(Vuex)

//定义全局变量componentId
var store = new Vuex.Store({
  state: {
    componentId:"",
  }
})

new Vue({
  el: '#app',
  router,
  store,  //挂载一下前面定义的store
  components: { App },
  template: ''
})

步骤二:

经过 前面的步骤,我们就可以监听全局变量componentId了,在组件A中:

<template>
	<div>
		<i class="iconfont icon-camera1" @click.self="cancel">
			<div v-show="showPop">
				//.......页面逻辑
			</div>
		</i>
	</div>
</template>

<script>
export default {
	data() {
		return {
			compId:'A',
			showPop:false,
		}
	},
	components: {},
	created () {},
	methods: {
		cancel() {
		this.showPop = !this.showPop;
		if (this.showPop) {  //将组件A的ID传给 this.$store.state.componentId
        	this.$store.state.componentId = this.compId;
        	return this.$store.state.componentId
      		}
		},
	},
	computed:{
    listenComponentState(){
      return this.$store.state.componentId
      }
   },
   watch: {  //监听全局变量componentId的变化
    listenComponentState: function(val, oldval){
      if (val != this.compId) {
         this.showPop = false;
      }
    }
  },
};
</script>

同上,在组件B中:

<template>
	<div>
		<i class="iconfont icon-layers-1 category" @click.self="cancel">
			<div v-show="showPop">
				//.......页面逻辑
			</div>
		</i>
	</div>
</template>

<script>
export default {
	data() {
		return {
			compId:'B',
			showPop:false,
		}
	},
	components: {},
	created () {},
	methods: {
		cancel() {
		this.showPop = !this.showPop;
		if (this.showPop) {  //将组件B的ID传给 this.$store.state.componentId
        	this.$store.state.componentId = this.compId;
        	return this.$store.state.componentId
      		}
		},
	},
	computed:{
    listenComponentState(){
      return this.$store.state.componentId
      }
   },
   watch: {  //监听全局变量componentId的变化
    listenComponentState: function(val, oldval){
      if (val != this.compId) {
         this.showPop = false;
      }
    }
  },
};
</script>

你可能感兴趣的:(前端)