使用 vue 3 路由器传递变量

问题描述 投票:0回答:1

我在 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

要求:

  • 路线需要前往例如mydomain.com/sv/nyheter/title-id-or-other-of-news-item
  • 页面组件/视图需要获取标题、mediaURL、mediaType、内容和publishDate(内容可以很大)。
  • 页面必须能够重新加载

Chatgpt 建议使用 localStorage 或 Pinia,这似乎是一个不必要的解决方案,因为我只想将参数传递到新页面。

1。这是正确的方法吗?

2。如果是这样,我怎样才能使其能够访问状态变量?

vue.js vuejs3 vue-router
1个回答
0
投票

“状态”参数应该喜欢这样吗?

this.$router.push({path:`/${countryCode}/${this.newsSectionSlug}/${id}-${publishDate}`,query:{state:{...}}})

console.log(this.$route.query.state)

或者联系路径的状态,获取参数。

© www.soinside.com 2019 - 2024. All rights reserved.