vue刷新页面后在mounted中无法获取this.$route.path的真实值

想要在页面刷新后根据当前路由路径判断当先活跃的菜单,故期望通过this.$route.path来获取当前路径,但在created和mounted中this.$route.path值都为/。
解决:在mounted中使用setTimeout在定时器中获取path

mounted () {
    // 不使用setTimeout无法在created和mounted中获取到this.$route的实际值
    setTimeout(() => {
      const curPath = this.$route.path
      this.allMenus.find(it => {
        if (it.url && curPath.startsWith(it.url)) {
          this.activeId = it.id
          return true
        }
      })
    }, 100)
  },

参考:vue2.0页面刷新后无法从mounted中获取url(this.$route)信息的解决办法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: `this.$route` 和 `this.$router` 是 Vue.js 用于管理路由的两个对象,它们之间的区别如下: - `this.$route` 表示当前路由信息对象,包含了当前 URL 解析得到的信息,例如当前路由的路径、参数、查询参数等等; - `this.$router` 表示路由实例对象,可以用它来进行路由的跳转、监听路由事件等等。 下面是一个简单的例子来说明它们的区别: ```html <template> <div> <h1>{{ $route.path }}</h1> <router-link to="/about">关于我们</router-link> <router-link to="/contact">联系我们</router-link> </div> </template> <script> export default { mounted() { // 通过 $router.push 跳转到/about 页面 this.$router.push('/about') // 监听路由变化事件 this.$router.afterEach((to, from) => { console.log('从', from.path, '跳转到', to.path) }) } } </script> ``` 在上面的例子,我们通过 `$route.path` 来获取当前路由的路径,并通过 `$router.push` 来跳转到 `/about` 页面。同时,我们还使用 `$router.afterEach` 来监听路由的变化事件,当路由发生变化时会打印出相应的信息。 ### 回答2: this.$route是一个在Vue实例内部可用的路由信息对象,包含当前路由的各种属性,比如路径、参数、查询等。this.$router是一个用来控制路由跳转的工具对象,可以通过调用它的方法来实现路由的跳转。 举个例子来说明区别。假设我们有一个简单的Vue应用,有两个组件:Home和About。在路由配置,我们设置了两个路径:"/home"和"/about"。 当我们在Home组件获取当前路由的路径时,我们可以使用this.$route.path。例如,我们可以在Home组件的模板使用 {{ this.$route.path }} 来显示当前路径。当我们访问"/home"时,模板显示的内容就是"/home"。 而如果我们要跳转到About组件,可以使用this.$router.push("/about")。假设在Home组件有一个按钮,点击按钮后即可跳转到About组件。我们可以在按钮点击事件调用this.$router.push方法实现跳转。 总结一下,this.$route是一个用来获取当前路由信息的对象,而this.$router则是一个用来控制路由跳转的工具对象。 ### 回答3: this.$route和this.$router都是Vue.js用于路由的属性。 this.$route是一个包含当前路由信息的对象,它包含了当前页面的路径、参数、查询参数等信息。我们可以通过this.$route来访问这些信息。 例如,假设我们的网址是http://example.com/home?id=1,我们可以通过this.$route.path获取当前路径,通过this.$route.query来获取查询参数,如下所示: ``` // 当前路径 this.$route.path // 输出:"/home" // 查询参数 this.$route.query.id // 输出:"1" ``` this.$router是Vue.js的路由器对象,它用于实现路由的跳转和导航。通过this.$router,我们可以使用编程式的方式实现页面之间的切换。 例如,我们可以通过this.$router.push来导航到一个新的页面: ``` // 导航到/home页面 this.$router.push('/home') ``` 或者我们可以使用this.$router.replace来替换当前页面的路由: ``` // 替换当前页面的路由为/home this.$router.replace('/home') ``` 总结起来,this.$route是用于访问当前路由信息的对象,而this.$router是用于路由的导航和跳转的对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值