【问题标题】:How to use vuex getter inside the onMounted method in vue?如何在 vue 的 onMounted 方法中使用 vuex getter?
【发布时间】:2021-06-25 18:34:17
【问题描述】:

我从我在 vuex 中使用的数据库中获取数据。我在 setup 方法中使用 getter 检索它,但我想在呈现页面之前使用其中的一些数据,最好是在 onMounted 方法中。我不知道如何使用 Compositions API 来做到这一点。这是我的代码:

setup() {
   const store = useStore();

   //store.dispatch(Actions.LOAD_COMMUNITY);
   onMounted(() => {
     store.dispatch(Actions.LOAD_COMMUNITY);
     setCurrentPageTitle(this.community.communityName);
   });

   return {
     community: computed(() => store.getters.currentCommunity),
   };
 },

当我这样做时,我得到一个“找不到名称'community'”错误,我无法通过使用 this.community 来修复它。

如果你们能帮我解决这个问题,我将不胜感激。

【问题讨论】:

    标签: javascript vue.js frontend vuex vue-composition-api


    【解决方案1】:

    this 不应该与组合 API 和 setup 一起使用。组件实例在setup 中不可用,但在特殊情况下可以使用getCurrentInstance() 访问。

    应该是:

       const community = computed(() => store.getters.currentCommunity),
    
       onMounted(() => {
         ...
         setCurrentPageTitle(unref(community).communityName);
       });
    
       return { community };
    

    【讨论】:

    • 感谢您的想法。实施后,我收到错误:“类型'ComputedRef '上不存在属性'communityName'”。你知道为什么吗?
    • 这是一个 TS 错误,表明存在问题。这是一个参考,应该这样对待。同样在您的代码中,您将操作视为同步,而实际上它可能是异步的。
    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2016-08-10
    • 2019-10-19
    • 2021-05-26
    • 2021-04-26
    • 1970-01-01
    相关资源
    最近更新 更多