【问题标题】:How to re-render component after update data in store如何在存储中更新数据后重新渲染组件
【发布时间】:2021-04-25 05:11:32
【问题描述】:

当我的store 中的数据更新时,我在重新渲染我的table 组件时遇到问题, 我有一张带有v-for 的简单表格,如下所示:

<tr v-for="d in getDatas" v-bind:key="d.id">

和改变页面的按钮:

<button class="fa fa-chevron-left" @click="previousPage"/>
<button class="fa fa-chevron-right" @click="nextPage"/>

我在打开组件之前将数据加载到我的数据中,这个表在哪里,我从存储中获取这些数据,如下所示:

  computed: {
    getDatas () {
      return this.$store.getters.getDatas;
    }
  },

但是当我点击按钮nextPagepreviousPage 时,如何使用data 更新我的商店? 这是我的方法:

  methods: {
      ...mapActions(["fetchDatas"]), //this is my action
      nextPage() {
        this.currentPage += 1;
      },
      previousPage() {
        if(this.currentPage != 1) {
          this.currentPage -= 1;
        }
      },

和我的行动:

    async fetchDatas({ commit },{ currentPage}) {
        const data = await fetch(`someURL&perPage=${currentPage}`);
        const response = await data.json();
        commit('setData', response);
    }

那么,当我点击我的next/previousPage 时,如何重新加载组件和我的商店?

【问题讨论】:

    标签: javascript typescript vue.js vuex


    【解决方案1】:

    您已经拥有一个computed 属性,该属性会在您的商店更新时自动更新。您所要做的就是在更改页面的方法中触发操作。

    nextPage() {
       this.currentPage += 1;
       this.fetchDatas(this.currentPage);
    },
    previousPage() {
       if(this.currentPage != 1) {
          this.currentPage -= 1;
          this.fetchDatas(this.currentPage);
       }
    },
    

    除非您有令人信服的理由要求操作中使用 Object 参数,否则我会完全删除花括号:

    async fetchDatas({ commit }, currentPage) {
    ...
    

    否则你需要用this.fetchData({currentPage: this.currentPage})来调用它。

    【讨论】:

    • 我做到了,但我的组件仍然没有重新加载新数据(我看到数据被正确获取):(
    • 尝试将您的计算结果替换为您商店中的实际 getter:...mapGetters(['getDatas']),
    【解决方案2】:

    您可以在 currentPagevariable 上设置一个监视,在单击按钮后,当当前页面发生变化时,getDatas 操作将再次触发。

    手表可以这样声明:

    watch: {
            currentPage: function (newValue) {
                this.$store.dispatch('fetchDatas', this.currentPage)
            },
    }
    

    【讨论】:

    • hmmm,如何在dispatch中添加参数fo fetchDatas?我问是因为我必须为这个动作提供一个论据
    • 抱歉错过了。你可以这样添加:this.$store.dispatch('fetchDatas', currentPage)
    • 哦,没关系,我在将参数传递给动作时有一个错误,它可以工作!非常感谢!
    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 2016-01-18
    • 2017-10-26
    • 2021-01-16
    • 2020-02-20
    • 2021-10-27
    • 2021-02-15
    • 2018-10-15
    相关资源
    最近更新 更多