首页 > 解决方案 > 为什么路由器查询不会在 nuxt 中立即更新?

问题描述

当我触发更新查询的函数时,url 变为 '?test=1' 但查询的控制台日志仍然为空。

methods: {
  test() {
    this.$router.push({ query: { test: 1 } });
    console.log(this.$route.query);
  }
}

但是我在 Vue 中使用了相同的方法。查询的控制台日志获取 {test:'1'} 工作正常。如果我想立即在 Nuxt 中得到正确的查询,我该怎么办?我知道有两种方法可以工作

  1. 手表
  2. setTimeout(()=>{console.log(this.$route.query)},0);

但我想使用更好的解决方案,还有其他方法可以吗?

标签: vue.jsnuxt.jsvue-router

解决方案


您可以使用watchon $route.query

methods: {
  test() {
    this.$router.push({ query: { test: 1 } });
  },
},
watch: {
  '$route.query'(q) {
    console.log(q);
  },
},

推荐阅读