我正在尝试创建相当常见的东西,让我们认为它是一个博客。在客户端,单击明信片将打开包含帖子内容的模式,并向 URL 添加查询
?postID=123
。
当我们尝试访问
my-site.com?postID=123
时,服务器中间件会检查是否存在 postID
查询参数,并通过 301 重定向将我们重定向到 my-site.com/category/subcategory/123
。这个中间件可能看起来像这样:
export default async function ({ route, redirect, api }) {
const postID = route.query.postID;
if (!postID) return;
const post = await api.get('postID')
redirect(301, `/${post.category}/${post.subcategory}/${postID}`);
}
它有效,但要与类别和子类别建立链接,我已经得到了我的帖子。在
_post
页面上,我们被重定向到我必须在 asyncData()
或 fetch()
中再次获取我的帖子。
我可以通过
nuxtServerInit
操作将帖子发布到商店,但在我看来,这有点黑客行为。
所以问题是:有没有办法在重定向期间将一些数据传递给页面组件?
我相信,是的,你能做到。但您需要了解一些事情。 如果您有命名路线,那就更简单了。只需执行以下操作:
// pass params to named route
this.$router.push ({name: 'user', params: {userId: '123'}})
// get params from named route in other component
console.log(this.$router.params)
但是,如果您没有创建命名路由,您可以做一些不太优雅的事情,但它会起作用......
通过此链接查看 vue 文档会很有趣 https://router.vuejs.org/guide/essentials/navigation.html。这里有很多信息可以更好地解释这一点。
但是让我们看一下示例,假设您使用 router.push,并且您了解可以在替换发生后执行一个函数,那么您可以执行以下操作:
this.$router.push(
{
path: 'YOUR/PATH',
},
// onComplete Function
(myValue) => {
// save the value in localStorage
localStorage.setItem('VALUE', JSON.stringify(myValue))
// to retrieve the value you can get with
console.log(JSON.parse(localStorage.getItem('VALUE')))
// save the value in store with vuex
this.$store.dispatch('doSomethingFromAction', myValue)
this.$store.commit('doSomethingFromMutation', myValue)
// to retrieve the value you can get with
console.log(this.$store.state.myValue)
})
如果您不了解 vuex,请查看文档:https://vuex.vuejs.org/