vue / nuxt路由query参数变化,但是页面不刷新

在vue里面:在做搜索功能的时候,顶部是一个组件,当顶部组件传值给搜索页:

    tosearch() {
      this.search = $('#search').val()
      console.log(this.search)

      this.$router.push({
        path: '/search',
        query: {
          search: this.search,
        },
      })
    },

但是如果在搜索页面输入想要找的值,页面不刷新,这个时候可以 利用组件内守卫 beforeRouteUpdate 方法来触发请求方法

  beforeRouteUpdate(to, from, next) {
    console.log(to.query.search)
    this.getData(to.query.search)
    next()
  },
  created() {
    this.getData()
  },

methods:{
    getData(search) {
      if (search) {
        this.search = search
      } else {
        this.search = this.$route.query.search
      }
      console.log('search:', this.search)
    },

//下面是axios调用接口
}

在Nuxt里面:

https://zh.nuxtjs.org/docs/2.x/components-glossary/pages-watchquery/文档里有介绍

watchQuery键可以设置查询字符串的监视程序。如果定义的字符串发生更改,则将调用所有组件方法(asyncData,fetch(context),validate,layout等)。监视默认情况下处于禁用状态,以提高性能。

如果要为所有查询字符串设置监视程序,请设置watchQuery: true

watchQuery: ['search'],注意里面的search是query里的属性名

  watchQuery: true,
  watchQuery: ['search'],
  async asyncData({ $axios, query }) {
    let search = query.search
  },

猜你喜欢

转载自blog.csdn.net/qq_41160739/article/details/111220459