在 Vuex 存储中观察 URL 查询参数
Watch for URL query parameter in Vuex store
我在 Vuex 中使用 Nuxt.js,当有人使用某个参数(例如:https://example.com/?param=abc)进入我的网站时,我想触发一个突变,并将该参数传递给一个状态.
我试图查看 watchQuery 的文档 属性 https://nuxtjs.org/api/pages-watchquery, but there’s no examples about how to do this, I just found this 但我看不到如何使用 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 为查询字符串设置了一个观察器,这意味着它正在等待查询 change 而页面已经呈现,从而可以调用 [=11 之类的方法=] 再次。
由于您只想在用户 进入 页面时保存某个参数,然后将参数传递给状态,因此您只需要将 asyncData 方法移动到您想要从中获取的页面参数,您还需要从自动传递给 asyncData
的上下文中提取 store
和 query
,然后使用 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
}
}
我在 Vuex 中使用 Nuxt.js,当有人使用某个参数(例如:https://example.com/?param=abc)进入我的网站时,我想触发一个突变,并将该参数传递给一个状态.
我试图查看 watchQuery 的文档 属性 https://nuxtjs.org/api/pages-watchquery, but there’s no examples about how to do this, I just found this
我试过写:
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 为查询字符串设置了一个观察器,这意味着它正在等待查询 change 而页面已经呈现,从而可以调用 [=11 之类的方法=] 再次。
由于您只想在用户 进入 页面时保存某个参数,然后将参数传递给状态,因此您只需要将 asyncData 方法移动到您想要从中获取的页面参数,您还需要从自动传递给 asyncData
的上下文中提取 store
和 query
,然后使用 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
}
}