【问题标题】:Vuex state and vue-routerVuex 状态和 vue-router
【发布时间】:2023-03-06 04:27:01
【问题描述】:

我正在尝试使用 vuejs 制作博客,但我有点卡住了。 我所有的文章数据都在这样的 Vuex 商店中:

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>


当我点击一个网格文章时,我希望它重定向到 articlePage.vue 组件,其中包含相同 id 文章的数据。

到目前为止,在我的 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,并访问正确的数据。但它不起作用。我做错了什么?

感谢您的帮助! :)

【问题讨论】:

  • 您的路由器配置是什么样的?您是否看到任何错误消息,或者 ID 参数是否包含您期望的内容,或者文章数据没有显示,或者组件本身没有加载,还是什么? (“它不工作”很少有足够的信息继续下去;我们需要细节。)
  • 是的,对不起,我的错应该更具体!我没有错误消息,当我 console.log(this.$store.state.articles) 我有包含所有数据的数组时,没关系!并且组件本身没有加载
  • 即使它不是“最好”的 vue 方式(以下所有答案都是很好的答案,使用 vuex getter 和 props,使用 find 而不是 filter 或使用 name 和 @987654329 @ 为您的router-link),您的代码实际上有效(fiddle here)。也许您只是忘记了router-view
  • 哇,我很困惑,我很确定几个小时前它没有工作......我又试了一次,看起来还可以。巫术。

标签: javascript arrays vue.js vuex vue-router


【解决方案1】:

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

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"],
...}

【讨论】:

    【解决方案2】:

    Name your routes 并像这样传递您的 articleId

    <router-link :to="{ name: 'article', params: { id: article.id }}">{{article.title}}</router-link>
    

    此外,使用 Array.prototype.find 可能比使用 Array.prototype.filter 更好,因为在您的情况下,第二个会为您提供一个单元素数组。

    【讨论】:

    • 我按照你的方法试过了,但仍然没有错误,组件没有显示。当我 console.log(this.$store.state.articles) 时我可以看到数组
    【解决方案3】:

    您应该使用find 而不是filter,并在查找回调函数中添加return

    selectedArticle() {
    
      let article = this.$store.state.articles.find(article => {
    
        return article.id == this.$route.params.id
    
      });
    
      return article;
    
    }

    【讨论】:

    • 组件无法正常加载,感谢您的帮助!
    猜你喜欢
    • 2020-01-20
    • 2023-03-20
    • 2020-01-20
    • 2017-07-25
    • 2019-05-24
    • 2021-04-11
    • 2019-11-11
    • 2017-04-13
    • 2017-02-17
    相关资源
    最近更新 更多