vuejs2 - 关注 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);
})
},
}
但是这种语法是不允许的。
欢迎任何帮助,在此先感谢!
解决方案
据我了解,watchQuery 为查询字符串设置了一个观察者,这意味着它正在等待查询更改,而页面已经呈现,从而可以再次调用类似的方法asyncData()
。
由于您只想在用户进入页面时保存某个参数,然后将参数传递给状态,您只需将 asyncData 方法移动到要从中获取参数的页面,您还需要提取store
和query
从上下文中自动传入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
}
}
推荐阅读
- ssl - 即使应用了重定向,WWW 子域也不安全
- azureservicebus - 向 Azure 服务总线订阅添加筛选条件
- r - 如何使用 WikipediR 包或 API 查询维基百科?
- batch-file - 如何只删除除少数文件外的文本文件
- matlab - 创建 1000x252 路径模拟
- python - 有没有办法修复pdfminer中的行对齐?
- c++ - Qml listview将新行添加到模型中的子向量
- python - 是否可以训练 spacy 来识别任何随机的组织名称
- django - Django 在电子邮件模板中请求用户名以及单击后如何将对象移动到接受或拒绝文件夹
- ios - 在 RxSwift 中处理绑定时如何不使观察者无效?