VueX:等到商店数据加载

5 javascript vue.js vuex

我目前一直在尝试显示一个表单来编辑现有网站。

我的问题是一个站点有大约 60 个输入字段,并且为每个输入编写 setter 和 getter 似乎不是一个好方法。

所以我能想到的最好的事情是将我的商店数据保存到一个局部变量,编辑局部变量并将其发送回来。

编辑.vue

<b-form-input id="currentSiteName" v-model="this.editSite.title"></b-form-input>

...
computed: {
  editSite() {
    return this.$store.state.currentSite
  }
},
mounted: function() {
  this.$store.dispatch('SHOW_SITE', {
    siteId: this.$route.params.id
  });
},
Run Code Online (Sandbox Code Playgroud)

存储操作

SHOW_SITE: function ({ commit }, siteParams) {
  http.get('/sites/' + siteParams.siteId).then((response) => {
      commit('SHOW_SITE', {
        site: response.data.foundSite
      });
    },
    (err) => {
      // eslint-disable-next-line
      console.log(err);
    })
},
Run Code Online (Sandbox Code Playgroud)

存储突变

SHOW_SITE: (state, { site }) => {
    state.currentSite = site;
},
Run Code Online (Sandbox Code Playgroud)

如果我查看我的 vue-dev-tools,我可以看到 editSite 具有正确的值,并且这些值都显示在表单中,但出现以下两个错误:

Error in event handler for "input": "TypeError: Cannot read property 'editSite' of null"

Cannot read property 'editSite' of null at callback
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么,还是有更好的 / c 方法来解决我的问题?

任何帮助将不胜感激!

小智 8

您应该使用 getter 来访问存储状态。

import { mapGetters, mapActions } from 'vuex'

async mounted() {
  await this.showSite(this.$route.params.id);
},
computed: {
  ...mapGetters([
    'currentSite',
  ]),
},
methods: {
  ...mapActions([
    'showSite'
  ]),
},
Run Code Online (Sandbox Code Playgroud)

现在,通过这种方式,您应该能够访问存储状态而不会出现 null 异常。你应该对 http.get 使用 async await。这样你的代码看起来更干净。

  • 使用mapGetters 与mapState 有区别吗?为了数据? (3认同)