【问题标题】:Vuex action not updating state when calling from component everytime每次从组件调用时,Vuex 操作都不会更新状态
【发布时间】:2021-01-10 15:37:11
【问题描述】:

我正在尝试使用 vuex 过滤我的博客文章。在我的路线更改时,我正在从我的 URL 更新数据以获取类别名称,然后将其用作操作负载。我在方法中执行此操作并在“已安装”中调用该方法。我的计算有获取博客状态的方法。现在过滤有时起作用,有时不起作用。没有错误显示。只有 getter 才能获得初始状态的状态。我是 Vuex 的新手。这是我的代码。想知道我在这里做错了什么,是否有任何最佳方法可以做到这一点:

我的 store.js:

state: {

        blogpost: [],

    },
    getters: {
        getblogPost(state) {
            return state.blogpost
        },

    },
    actions: {
        getblogPost(context) {
            axios.get('/blogpost')
                .then((response) => {
                    // console.log(response.data)
                    context.commit('getblogPost', response.data.posts)
                })
        },
        getPostByCatName(context, payload) {
            axios.get('/categorypost/' + payload)
                .then((response) => {
                    console.log(response.data.posts)
                    context.commit('getPostByCatName', response.data.posts)
                })
        },

    },
    mutations: {
        getblogPost(state, payload) {
            return state.blogpost = payload
        },
        getPostByCatName(state, payload) {
            state.blogpost = payload
        },

    }

这是我的组件的脚本。我想要的只是每次都用过滤后的博客填充 allPost(),而不是某个时候!

data() {
        return {
            categoryName: this.$route.params.catName,
        }
    },

    computed: {
        allposts() {
            return this.$store.getters.getblogPost
        }
    },
    mounted() {
        this.filterPosts()
        this.$store.dispatch("getblogPost")


    },
    methods: {
        filterPosts() {
            this.$store.dispatch('getPostByCatName',
                this.categoryName);
        }
    }

【问题讨论】:

标签: vue.js vuex


【解决方案1】:

我的建议是使用计算属性,而不是方法

computed: {
  filteredPosts() {
    return this.$store.getters.getblogPost.map(x => x.category === this.$route.params.catName;
  }
}

计算属性比方法“更具反应性”。这样您就依赖于数据反应性,而不是获得正确的方法序列

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多