在 vuejs 中引用路由器链路参数数据



>我有这个组件

<div class="card col-4" style="width: 22rem;">
<img class="card-img-top" src="../assets/images/olu.jpg" alt="Card image cap">
<div class="card-block">
<h4 class="card-title">Card title</h4>
<p class="card-text">{{ stories.articles[0].summary }}</p>
<router-link :to="{path: '/viewArticle', params:{id:123}}"><a class="btn btn-primary">Continue Reading</a></router-link>
</div>
</div>

请注意路由器链路标记:

<router-link :to="{path: '/viewArticle', params:{id:123}}"><a class="btn btn-primary">Continue Reading</a></router-link>

它被路由以显示一个 article.vue 组件,如下所示:

<template>
<div>
<div class="container row">
<h1 class="display-3 col">Article in view</h1>
</div>
<div class="container">
<img src="../assets/images/olu.jpg"/>
<article>
some text
</article>
</div>
</div>
</template>
<script>
// /console.log(params.id);
export default {
name: 'article',
data() {
return {
}
}
}
</script>

这绝对没问题。我的问题非常简单,如何引用传入 article.vue 组件中的路由器链接参数属性的 id 值,每当点击/viewArticle 路径时都会返回该值,如上面的第一个组件所示。

我尝试浏览文档和几篇文章,但到目前为止,我还没有找到合适的解决方案。

亲切问候

您可以将props属性设置为文章路由上的true,如将 props 传递到路由器组件部分中所述。

{
name: 'article'
path: '/viewArticle/:id',
component: ArticleView // whatever you named the component
props: true
}

然后你ArticleView组件可以添加一个id道具:

<script>
export default {
name: 'article',
props: ['id'],
data() {
return {
}
}
}
</script>

现在,您可以直接在组件上使用该id,您可以获取文章。

如果需要,还可以预加载文章,以便传递实际文章而不是 id。

您可以通过将 beforeRouteEnter 添加到组件来执行此操作:

<script>
export default {
name: 'article',
props: ['id'],
data() {
return {
article: null,
}
},
beforeRouteEnter (to, from, next) {
// your ajax stuff goes here
// I use axios in this example
axios.get(`/api/article/${to.params.id}`)
.then((article) => {
next(vm => {
vm.article = article
})
})
.catch(() => {
next('/404')
})
}
}
</script>

因此,在输入路由器之前,它将获取文章。这还有一个额外的优势,即所有组件代码都可以假定您已经加载了文章。您不必处理已加载或未加载的情况。

此外,您还可以像这样访问匹配的路由:this.$route和路由器进行如下导航:this.$router(末尾带有 r)。

最新更新