uni-app vue3模式下nvue页面无法通过computed获取vuex改变后的值

uni-app vue3模式下nvue页面无法通过computed获取vuex改变后的值

开发环境 版本号 项目创建方式
Windows 10 HBuilderX

示例代码:

computed: {  
    gettoken() {  
        return this.$store.state.token;  
    }  
}
6 回复

vue3下nvue页面使用vuex时最好使用getApp().$store.state的方式,我之前使用组合式api时也出现vuex状态不更新的情况,发帖后有管理员这样指导我的,很有效

更多关于uni-app vue3模式下nvue页面无法通过computed获取vuex改变后的值的实战教程也可以访问 https://www.itying.com/category-93-b0.html


计算属性没有调用 可以用一下方法: <template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{ title }}</text>
</view>
<button type=“default” @click=“submit()”>修改</button>
<text>{{ token }}</text>
</view>
</template>

<script> export default { data() { return { title: 'Hello', token:'' }; }, onLoad() {}, computed: { gettoken() { console.log("gettoken"); return this.$store.state.token; } }, methods: { submit() { this.$store.dispatch('login', { token: '登录了' }).then(res => { console.log(res); console.log(this.$store.state.token); this.token = this.$store.state.token this.$forceUpdate(); }); } } }; </script> <style> </style>

HBuilder X 3.4.3-alpha已支持

现在tabbar页面只有首页能获取vuex变化后的值,其他tabbar页面不行。非tabbar页面可以获取但是会执行2次computed。watch,watchEffect可以正常工作

注意computed被模板使用才会被执行,获取vuex的变化,computed,watch,watchEffect均可正常工作

在 uni-app 的 Vue 3 模式下,nvue 页面中 computed 无法响应 Vuex 状态变化,通常是由于 Vue 3 的响应式系统与 nvue 的渲染机制差异导致的。以下是解决方案:

  1. 使用 Composition API:在 setup() 函数中,通过 computed 从 Vuex 获取状态,并确保使用 refreactive 包装返回值以保持响应性。

    import { computed } from 'vue';
    import { useStore } from 'vuex';
    
    export default {
      setup() {
        const store = useStore();
        const token = computed(() => store.state.token);
        return { token };
      }
    };
    
  2. 使用 mapState 辅助函数:如果仍使用 Options API,通过 mapState 将 Vuex 状态映射为计算属性,确保在 nvue 中正确触发更新。

    import { mapState } from 'vuex';
    
    export default {
      computed: {
        ...mapState(['token'])
      }
    };
回到顶部