今天聊一聊vue页面监听store值改变

本文详细介绍了如何在 Vue 项目中使用 Vuex 进行模块化的状态管理,包括消息列表的设置、存储与更新,以及通过 computed 属性和深度监听来实时响应数据变化。通过实例展示了在权限管理模块中,如何存储和获取消息列表,以及在组件中正确地使用这些数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先建立store:

import router, { rootRoute, exceptionRoutes, filterAsyncRoutes } from '@/routes'
import asyncRoutes from '@/routes/asyncRoutes'
import config from '@/utils/config'
import { length } from '@/utils'
import request from '@/api'

export default {
  namespaced: true,
  state: {
    messageList:[],//消息列表
  },
  mutations: {
    //聊天消息储存
    SET_MESSAGELIST:(state, info)=>{
      let data = Object.assign([], state.messageList ,info)
      state.messageList = data
    },
  },
  actions: {
    
    },
    // 同步缓存页面
    AsyncIncludes ({ commit, state }, data) {
      commit('SET_INCLUDES', data)
    },
    // 新增缓存页面
    AddIncludes ({ commit, state }, path) {
      let includes = state.includes
      if (includes.indexOf(path) < 0) {
        includes.push(path)
      }
      commit('SET_INCLUDES', includes)
    },
    // 删除缓存页面
    DelIncludes ({ commit, state }, path) {
      let includes = state.includes.filter(i => i !== path)
      commit('SET_INCLUDES', includes)
    },
    // 退出
    Logout ({ commit }) {
      commit('SET_OUT')
    }
  },
  getters: {
    includes: state => state.includes,
    get_CustomerList: state => state.customerList,
    get_ExpertList: state => state.expertList,
  }
}

重点是:

SET_MESSAGELIST:(state, info)=>{
      let data = Object.assign([], state.messageList ,info)
      state.messageList = data
    }

然后是存值:

hat.$store.commit('permission/SET_MESSAGELIST', that.conversationList)

一定带上模块名称(permission)。

然后是使用computed计算属性取值:

 computed: {

        cuserList() {

            return this.$store.state.permission.messageList;

        },

    },

使用深度监听新值变化:

watch:{     //监听value的变化,进行相应的操做便可
    fuid: function(a,b){     //a是value的新值,b是旧值
      this.uid = this.fuid;
      this.chatList =[]
      this.getChatList();
    },
    cuserList: {
        handler(nval, oval) {
          debugger
          if(nval.length>0){
              this.userList.forEach(item=>{
                nval.forEach(item2=>{
                  if(item.uid==item2.send_uid && this.uid ==item2.receive_uid){
                   item.unreadCount = item.unreadCount+1;
                   item.msg_type = item2.msg_type;
                   item.msg_content = item2.msg_content;
                  }
                  if(item.uid==item2.send_uid && this.uid ==item2.receive_uid){
                   item.unreadCount = item.unreadCount+1;
                   item.msg_type = item2.msg_type;
                   item.msg_content = item2.msg_content;
                  }
                })
              })
              console.log(this.userList)
          }
        },
        deep: true, // 深度监听
        immediate: true,//立即执行
    },
  },

完毕,这样能解决绝大部分问题。

### 实现 Vue 页面监听 Vuex Store 的方法 为了实现在 Vue 页面监听 Vuex store 中的状态变化,可以采用 `computed` 和 `watch` 组合的方式。通过定义计算属性来访问 Vuex state,并利用侦听器观察这些计算属性的变化。 #### 使用 Computed 访问 State 数据 在组件内部创建个名为 `newData()` 的计算属性用于映射 Vuex store 中的特定状态字段: ```javascript export default { name: 'YourComponentName', computed: { newData() { return this.$store.state.listData; // 获取 listData 状态 ^[3] } }, } ``` 此部分代码使得每当 Vuex store 内部的 `listData` 发生更新时,该计算属性会自动重新求值并反映最新情况^[3]。 #### Watcher 监控 Data 变化 紧接着,在同组件内设置 watcher 来监视上述计算属性的新值变动事件。旦检测到任何更改,则执行相应的处理逻辑: ```javascript export default { ... watch: { newData: { immediate: true, // 初始化即刻触发次回调函数 deep: true, // 对象嵌套情况下启用深度监控 handler(newValue) { console.log('Detected change:', newValue); this.show_data = newValue; } } } } ``` 这里配置了两个选项参数:`immediate` 设置为 `true` 表示初始化阶段也会立即调用处理器;而 `deep` 则确保能够追踪对象内部深层次结构上的修改^[3]^。 另外需要注意的是,如果遇到子页面首次加载时不响应 vuex 变化的现象,可能是因为异步操作未完成就进行了渲染所致。对于这种情况,可以在发起请求前加入 loading 或者其他提示机制告知用户当前处于等待状态,同时确认 dispatch 动作是否成功返回预期的结果^[2]^。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值