vue.js - VueJS router.push 不更新页面内的数据

标签 vue.js nuxt.js

我正在使用 NuxtJS,并且我有一个导航栏,可以转到 /website?web=1/website?web=2.. 当我从 >/website?web=1/website?web=2 反之亦然。.我的 async fetch 根本没有运行。

website.vue

async fetch({ store, error, route, params }) {
    let parameters;
    const pageLimit = store.state.websites.pageLimit;
    const offset = params.id ? (params.id - 1) * pageLimit : 0;
    const web = route.query.web;
    try {
      if (web === "1") {
        parameters = `?&is_global=true&offset=${offset}&limit=${pageLimit}`;
      } else if (web === "2") {
        parameters = `?&is_global=false&offset=${offset}&limit=${pageLimit}`;
      } else {
        parameters = `?co_id=${
          route.query.co_id ? route.query.co_id : ""
        }&ca_id=${
          route.query.ca_id ? route.query.ca_id : ""
        }&limit=${pageLimit}&offset=${offset}`;
      }
      await Promise.all([

        store.dispatch("websites/fetchWebsites", parameters)
      ]);
    } catch (e) {
      console.log("Error: " + e);
    }
  },

NavBar.vue

methods: {
    handleClick(tab, event) {
      switch (tab.label) {
        case "1":
          this.$router.push({ name: "index" });
          break;
        case "2":
          this.$router.push("/country");
          break;
        case "3":
          this.$router.push("/website?web=1");
          break;
        case "4":
          this.$router.push("/website?web=2");
          break;
      }
    }
  }

最佳答案

当使用Nuxt的fetch()时,你需要一个显式的观察者来监听路由变化。

对于具有 async fetch() 的 Nuxt 组件,如果您希望它在路由更改时更新,请设置一个标准观察程序。

参见文档:https://nuxtjs.org/docs/2.x/features/data-fetching#listening-to-query-string-changes

export default {

  watch: {
      '$route.query': '$fetch'   // This runs $fetch, defined below
  },

  async fetch() {
      // Runs on server load (SSR), or when called (see above)
  }

}

对于其他上下文(或 Nuxt 2.12 之前):

您可以使用 watchQuery 进行探索。

参见文档:https://nuxtjs.org/docs/2.x/components-glossary/pages-watchquery/

export default {

  watchQuery(newQuery, oldQuery) {
    // Only execute component methods if the old query string contained `bar`
    // and the new query string contains `foo`
    return newQuery.foo && oldQuery.bar
  }

}

https://nuxtjs.org/docs/2.x/components-glossary/pages-watchquery/

关于vue.js - VueJS router.push 不更新页面内的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60825076/

相关文章:

javascript - NUXT如何将数据从页面传递到布局

typescript - 使用 Vue 构建 TypeScript 代码时 Webpack 构建错误

javascript - VueJs 插入嵌套列表

node.js - Nuxt.js 刷新 url 找不到 404

vue.js - [Vue警告] : Failed to resolve directive: clipboard

nuxt.js - 如何在 nuxt.config.js 中正确导入组件以用作自定义图标?

javascript - 构建失败后 Electron 将文件添加到公用文件夹

javascript - Vuex:从另一个模块访问状态

vue.js - Vuex - 不要在突变处理程序之外改变 vuex 存储状态

webpack - NuxtJS & SASS Loader - 在生产环境中使用 sass-loader (SCSS) 构建