4

注意避坑,Vue Router 4: 路由参数在 created/setup 时不可用

 1 year ago
source link: https://www.fly63.com/article/detial/11666
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

你的可能已经注意到,vue 3版本的 Vue router (4.0) 与其之前的版本有一些 breaking change 更改。大部分的 Vue Router api 都没有变化,而且迁移过程也非常直接。然而,一个非常不明显但重要的变化常常被忽视,它可能导致难以调试的行为。现在所有的导航都是异步的

如果你想知道为什么 URL中的查询参数在你的 setup 方法或 created 钩子中无处可寻,但当插入它们时,它们仍然出现在模板中,不要离开, 我们来一探究竟。

现在所有的导航都是异步的

为了探索这一点,我们将使用一个已经安装了Vue router 4.0 的Vue 3 骨架应用的 barebones 。你可以在这个 repo 中跟着代码走。

地址:https://github.com/Code-Pop/router-4-async

项目下载下来后,运行 npm iinstall 然后 运行 npm run serve,界面如下所示:

629eb7c08198d.jpg

如果你现在在URL中添加一些查询参数,如

<a href="http://localhost:8080/?param=1" target="blank">http://localhost:8080/?param=1</a>

页面会刷新,并将参数显示在界面上。

629eb7c489406.jpg

让我们看一下App.vue里面内容,我们在组件中添加了一个 created 的钩子。你会看到一个console.log行,它打印$router.query的内容,就像我们在模板中的那样。

<template>
  <div id="nav">
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </div>

  <router-view/>

  Query: 
  <pre>{{ $route.query }}</pre>
</template>

<script>
export default {
  data: () => ({}),
  created () {
    console.log(this.$route.query)
  }
}
</script>

我们继续,像刚才一样,使用和不使用查询参数再次运行这个实验。

你会注意到,无论添加多少个参数,或者重新加载多少次页面,控制台打印的this.$route.query都是空的。

接着,让我们来解开这个问题。

正如一开始提到的,一个经常被忽视的Vue Router 4的破坏性变化是,现在所有的导航都是异步的。正如文档所建议的那样,在处理 transition 时,这一点变得更加明显,因为当Router从空到被数据填充时,它将触发动画。

我们之所以能在浏览器中看到参数,但在控制台中却看不到,是因为Vue的响应式的,一旦Router的查询对象可用,就立即更新html。记住,它现在是异步的。这个过程很快,以至于对我们来说,它似乎一直都在那里,当在 setup 函数或生命周期钩子(如created())中处理查询参数时,这可能真的会令人困惑。

幸运的是,这个问题的解决办法是非常简单。我们只需到 main.js 中,等待路由 ready 好后再挂载程序,如下所示:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)

// Replace -> app.mount('#app')
router.isReady().then(() => {
    app.mount('#app')
})

现在,回到浏览器,添加参数并重新加载,就会在控制台上看到我们的参数信息了。

作者:Marina Mosti 译者:前端小智 来源:medium
原文:https://www.vmastery.com/blog/vue-router-4-rute-params-not-available-on-created-setup/

链接: https://www.fly63.com/article/detial/11666


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK