首页 > 解决方案 > 关注 Vuex 商店中的 URL 查询参数

问题描述

我正在将 Nuxt.js 与 Vuex 一起使用,我想在有人使用特定参数(例如:https ://example.com/?param=abc )进入我的网络时触发突变,并将参数传递给状态.

我试图检查 watchQuery 属性https://nuxtjs.org/api/pages-watchquery的文档,但是没有关于如何执行此操作的示例,我只是发现了这个How to watch on Route changes with Nuxt and asyncData但我看不到如何使用 watchQuery 在 Vuex 存储中编写操作的任何方式。

我试着写:

actions: {
    watchQuery: true,
    asyncData ({ query, app }) {
       const { start } = query
       const queryString = start ? `?start=${start}` : ''
       return app.$axios.$get(`apps/${queryString}`)
       .then(res => {
           commit('setParam',res.data);
       })
    },
}

但是这种语法是不允许的。

欢迎任何帮助,在此先感谢!

标签: vuejs2vuexnuxt.js

解决方案


据我了解,watchQuery 为查询字符串设置了一个观察者,这意味着它正在等待查询更改,而页面已经呈现,从而可以再次调用类似的方法asyncData()
由于您只想在用户进入页面时保存某个参数,然后将参数传递给状态,您只需将 asyncData 方法移动到要从中获取参数的页面,您还需要提取storequery从上下文中自动传入asyncData,然后使用store并将query查询参数保存到您的状态中。

这是一个简单的演示

// Your page from which you want to save the param
export default {
  asyncData({store, query}) { // here we extract the store and query
    store.state.somethingForSavingTheParam = query.nameOfTheParamYouWantToSave
     // instead of using store.state you could use store.commit(...) if that's what you want
  }
}

推荐阅读