场景如下图所示

切换主页面中的组织(即:改变组织id  orgid),需要刷新组件中的列表

当vuex中state变化时,子组件需要进行更新,怎么做?(三种方法)

第一种:通过改变router-view中的key来达到刷新组件的目的(野路子,推荐第三种)

当改变state中的值时,改变router-view中的key,这个key为时间戳

<router-view  :key="timeValue"/>
<script>

  export default {
    name: 'mainMenu',
    data() {
      return {
        orgid:'',
        timeValue:''
      }
    },
    computed: {
     
    },
    components: {
      
    },
    created() {
    
    },
    mounted() {
      
    },
    methods: {
      changeOr(){
        this.orgid = "23"
        this.$store.commit('ogrid',this.orgid);
        var timeNow = new Date().getTime();
        this.timeValue = timeNow 
       
      }
    },

  }
</script>

 第二种:用watch(两种方法不可共存,用第一种时,watch失效)

在子组件中,用watch监听

<script>

  export default {
    name: 'sub',
    data() {
      return {
       
      }
    },
    computed: {
     
    },
    watch:{
      '$store.state.orgid'(){
        alert('改变')
        this.initTable()
      }
    },
    components: {
      
    },
    created() {
    
    },
    mounted() {
      
    },
    methods: {
      initTable(){}
    },

  }
</script>

第三种 vue全局更新以及孙组件调用祖组件(利用provide和inject)

参考文章

vue全局更新以及孙组件调用祖组件(利用provide和inject)_有蝉的博客-CSDN博客_vue孙组件调用祖组件方法

Logo

前往低代码交流专区

更多推荐