我在 vue 3 中有一个使用选项 API 的 newsCard 组件。当用户单击此卡时,我希望他们转到显示完整新闻文章的页面。但是,我需要将一些数据传递给这篇完整的新闻文章,例如标题、mediaURL 和文本内容。我试图将其作为一种状态传递:
clickedCard() {
const countryCode = this.$route.params.countryCode || 'sv';
const id = this.blockData.id.slice(0, 10);
const publishDate = this.blockData.publishDate.split('T')[0].replace(/-/g, '');
this.$router.push({
path: `/${countryCode}/${this.newsSectionSlug}/${id}-${publishDate}`,
state: {
title: this.blockData.title,
mediaURL: this.blockData.mediaURL,
mediaType: this.blockData.mediaType,
defaultImage: this.defaultImage,
content: this.blockData.content,
publishDate: this.blockData.publishDate
}
});
}
我的路由器index.js 文件中包含以下内容:
{
path: '/:countryCode/:newsSectionSlug/:id-:publishDate',
name: 'NewsPage',
component: NewsPage,
props: true
}
现在,当我尝试在 NewsPage.vue 视图/组件中访问这些内容时,我无法访问。我控制台登录 NewsPage.vue:
mounted() {
console.log(this.$router.currentRoute.value)
}
这给了我这个(没有状态变量):
{fullPath: '/sv/nyheter/96427258-4-20240926', path: '/sv/nyheter/96427258-4-20240926', query: {…}, hash: '', name: 'NewsPage', …}
fullPath
:
"/sv/nyheter/96427258-4-20240926"
hash
:
""
href
:
"/sv/nyheter/96427258-4-20240926"
matched
:
[{…}]
meta
:
{}
name
:
"NewsPage"
params
:
countryCode
:
"sv"
id
:
"96427258"
newsSectionSlug
:
"nyheter"
publishDate
:
"4-20240926"
[[Prototype]]
:
Object
path
:
"/sv/nyheter/96427258-4-20240926"
query
:
{}
redirectedFrom
:
undefined
[[Prototype]]
:
Object
要求:
Chatgpt 建议使用 localStorage 或 Pinia,这似乎是一个不必要的解决方案,因为我只想将参数传递到新页面。
1。这是正确的方法吗?
2。如果是这样,我怎样才能使其能够访问状态变量?
“状态”参数应该喜欢这样吗?
this.$router.push({path:`/${countryCode}/${this.newsSectionSlug}/${id}-${publishDate}`,query:{state:{...}}})
console.log(this.$route.query.state)
或者联系路径的状态,获取参数。