wordpress做的学校网站/深圳建站公司
Vue监听vuex中对象属性变化的方法
需求分析:
store中有一个空对象monitorGetTargetList
页面上有多个按钮,每个按钮都有一个id
点击某个按钮之后,每隔一秒计算出一个数据,需要传到store的monitorGetTargetList
中,并放到对应按钮的id中
解决方法:
普通的vuex监听不能监听到对象中的属性以及属性值的变化,所以需要借助Object.assign()
来实现
注:
Object.assign()
方法接收多个参数,第一个参数为目标对象,第二个及其以后的参数为源对象,该方法会将所有源对象中的属性全部复制到目标对象中并返回。(若源对象中有重复的属性,后面的会把前面的乃至目标对象中的同名属性覆盖掉)
MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
代码示例:
store/index.js
const store = new Vuex.Store({state: {monitorGetTargetList: {}},getters: {getMonitorGetTargetList: state => state.monitorGetTargetList },mutations: {setMonitorGetTargetList(state, params) {const { id, data } = params;if(!state.monitorGetTargetList.hasOwnProperty(id)) {state.monitorGetTargetList = Object.assign({}, state.monitorGetTargetList, {[id]: []})}let arr = Array.from(state.monitorGetTargetList[id]);arr.push(data);state.monitorGetTargetList = Object.assign({}, state.monitorGetTargetList, {[id]: arr})}}
}export default store;
target.vue
<script>
import { mapGetters } from "vuex";export default {computed: {...mapGetters(["getMonitorGetTargetList"])},watch: {getMonitorGetTargetList(data) {console.log(data)}}
}
</script>