使用 vue-router 在浏览器上从 Vuex store.state 加载内容

Issue loading content from Vuex store.state on browser using vue-router

在阅读了 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')
});

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

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

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