【问题标题】:Issue loading content from Vuex store.state on browser using vue-router使用 vue-router 在浏览器上从 Vuex store.state 加载内容问题
【发布时间】:2019-07-29 22:10:01
【问题描述】:

在阅读了许多来自 Vue、Vuex 和 Vue-Router 的示例和文档后,我做了这个项目:https://jsfiddle.net/junihh/30wda1em/5/

当我尝试从 Post 部分加载一行时,即使一切正常,Vuex 存储中的值也是空的。这里是组件:

const PostContent = Vue.component('postcontent', {
    data() {
        return {
            post: this.$store.state.currentPost
            // post: {
            //     title: 'The title',
            //     content: 'The content for test.'
            // }
        }
    },
    template: getTemplate('#tpl-postcontent')
});

这里是更新 state.currentPost 值并调用“postcontent”组件的组件。

const Posts = Vue.component('posts', {
    data() {
        return {
            url_path: '/posts/content',
            rows: this.$store.state.dataAll
        }
    },
    methods: {
        openPost: function(e)
        {
            let rowID = e.currentTarget.getAttribute('data-rowid');

            let dataAll = this.$store.state.dataAll;
            let currentPost = dataAll.filter(row => (row.id == rowID))[0];

            this.$store.state.currentPost = currentPost;
        }
    },
    template: getTemplate('#tpl-posts')
});

这里有什么帮助吗?我被这个问题困住了。

【问题讨论】:

    标签: vuejs2 vue-component vuex vue-router


    【解决方案1】:

    您需要使用计算属性以反应性从您的商店收集信息:

    const PostContent = Vue.component('postcontent', {
      computed: {
        post() {
          return this.$store.state.currentPost
        }
      },
      template: getTemplate('#tpl-postcontent')
    });
    

    还要尽量避免在突变处理程序之外改变状态。您可以添加一个突变来设置您的currentPost,如下所示:

    <template id="tpl-posts">
      ...
        <li v-for="row in rows" :key="row.id">
          <router-link :to="url_path" @click.native="openPost(row.id)">
            {{ row.title }}
          </router-link>
        </li>
      ...
    </template>
    
    const Posts = Vue.component('posts', {
      //...
      methods: {
        openPost: function(id)
        {
          this.$store.commit('SET_CURRENT_POST', id)
        }
      },
      template: getTemplate('#tpl-posts')
    });
    
    const store = new Vuex.Store({
      state: {
        dataAll: {},
        currentPost: {}
      },
      mutations: {
        SET_CURRENT_POST: function(state, id) {
          let post = state.dataAll.find(data => data.id === id)
          state.currentPost = post
        }
      }
    });
    

    fiddle

    【讨论】:

    • 哇,您的回答超出了我的预期。我真的很感谢你的帮助。非常感谢@Sovalina :-)
    猜你喜欢
    • 2020-03-10
    • 2017-05-25
    • 1970-01-01
    • 2018-12-11
    • 2019-04-11
    • 2016-08-10
    • 2021-08-04
    • 2019-07-13
    • 1970-01-01
    相关资源
    最近更新 更多