javascript - Vuex 状态和 vue-router

标签 javascript arrays vue.js vuex vue-router

我正在尝试用 vuejs 制作一个博客,但我有点卡住了。 我所有的文章数据都在 Vuex Store 中,如下所示:

export const store = new Vuex.Store({    
state: {
    articles: [{
        title: "Article 1",
        id: 1,
        content:"Article 1 content"
    }, {   
        title: "Article 2",
        id: 2,
        content:"Article 2 content"
        }
    }]
}

我的主页上有一个文章网格:

<div class="item-article" v-for="article in articles">
   <router-link :to="{path: '/article/'+article.id}"></router-link>
   <div>{{ article.title }}</div>
</div>


当我点击网格文章时,我希望它重定向到带有相同 id 文章数据的articlePage.vue 组件。

到目前为止,在我的articlePage.vue组件上我是这样的:

<div v-for="article in selectedArticle">
   <h1>{{ article.title }}</h1>
   <p>{{ article.content }}</p>
</div>

computed: {
        selectedArticle(){
            return this.$store.state.articles.filter(article => article.id == this.$route.params.id);
        }
    }

我想使用 $route.params.id 来捕获 VueX 中匹配的 id,并访问正确的数据。但这不起作用。我做错了什么?

感谢您的帮助! :)

最佳答案

首先,定义您的路线并了解如何创建动态路线:

const routes = [
  {
    path: '/articles/:id',
    name: 'articles',
    component: articlePage,
    props: true
  }
]

在你的 Vue 实例中,传递 routesvuex store:

new Vue({
  store,
  router: routes,
  el: '#app',
  render: h => h(App)
})

在 Vuex Store 的 getters 属性中,您需要创建一个通过 id 过滤/查找文章的方法,如下所示:

getArticlesById: (state) => (id) => state.articles.find(article => article.id === id)

最后,在 Mounted() 方法中,调用他:

this.article = this.$store.getters.getArticlesById(this.articleId)

this.articleId 是 URL 发送的参数,记得在组件 props 中定义他:

export default {
  name: "articlePage",
  props: ["category"],
...}

关于javascript - Vuex 状态和 vue-router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52169797/

相关文章:

javascript - UglifyJS 'use strict' 语句

php - php数组中的反向范围类功能

java - 无限二维数组搜索

javascript - HTML & JS 标记 - 更好的方法可能吗?

javascript - 如何调用使用状态(由另一个函数设置)并更新状态的函数

vue.js - 如何在 Element UI 中使用 Font Awesome 5 图标

javascript - Vue.js:搜索栏组件 - 如果输入值长度 > 1,如何使重置按钮出现?

html - 使用 Vuejs 显示更多更少

javascript - 支持着色和纹理的 GLSL 着色器

arrays - 使用不同的阈值替换多列中的值