[Vue] When the state in vuex is changed, the subcomponent watch cannot detect changes in object values.

Article directory

Problem Description

  • state state file:
export default {
    
    
  namespaced: true,
  state: {
    
    
  	params: {
    
    
  	  aa: '',
  	  bb: [],
  	}
  },
  mutations: {
    
    
  	initParams(state) {
    
    
      state.params = {
    
    
        aa: '',
  	  	bb: [],
      };
    },
  },
  actions: {
    
    },
}
  • parent component
<template>
<child  childParams="params"/>
</template>

<script>
import {
      
       mapState } from 'vuex';
import child from '@/components/child';
export default {
      
      
  props: {
      
      
    options: Object,
  },
  components: {
      
       child },
  data() {
      
      
    return {
      
      };
  },
  computed: {
      
      
    ...mapState('we-server/insight', ['params']),
  },
  methods: {
      
      },
  watch: {
      
      
    options: {
      
      
      handler(now) {
      
      
      	// 当 options 改变的时候,给 params 添加一个新的属性
      	this.params.name = now.name;
      	// 这里打印是有值的,但是传递给子组件那边 watch 却监听不到
        console.log('64 params =', this.params.name); 
      },
      deep: true,
    },
  },
  mounted() {
      
      },
};
</script>

Solution

  • Just set an initialized attribute value forparams object
export default {
    
    
  namespaced: true,
  state: {
    
    
  	params: {
    
    
  	  aa: '',
  	  bb: [],
  	  name: '',
  	}
  },
  mutations: {
    
    
  	initParams(state) {
    
    
      state.params = {
    
    
        aa: '',
  	  	bb: [],
  	  	name: '',
      };
    },
  },
  actions: {
    
    },
}

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/133645563