【问题标题】:Watch for URL query parameter in Vuex store关注 Vuex 商店中的 URL 查询参数
【发布时间】:2019-05-22 04:52:36
【问题描述】:

我正在将 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 但我看不到如何在 Vuex 中编写操作使用 watchQuery 存储。

我试着写了:

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);
       })
    },
}

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

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

【问题讨论】:

    标签: vuejs2 vuex nuxt.js


    【解决方案1】:

    根据我的理解,watchQuery 为查询字符串设置了一个观察者,这意味着它正在等待查询更改,而页面已经呈现,从而可以再次调用像 asyncData() 这样的方法。
    由于您只想在用户进入页面时保存某个参数,然后将参数传递给状态,因此您只需将 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
      }
    }
    

    【讨论】:

    • 所以按照这个例子,在浏览器中输入这个 url https://example.com/?nameOfTheParamYouWantToSave=abc 应该保存 store.state.somethingForSavingTheParam:'abc' isn't it? 现在这样做我没有看到存储中保存的参数
    • @Joe82 这很奇怪,在发布答案之前它对我有用,即使现在它也有效。你在页面中有那个 asyncData 函数吗?不是布局?
    • 就在现场,我在我的布局页面中有它。把它移到一个页面上,效果很好!
    • 很高兴它工作!另外,如果您想在更多页面中使用它并且不想一遍又一遍地复制代码,您可以查看nuxtServerInit
    猜你喜欢
    • 1970-01-01
    • 2020-06-18
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2020-01-21
    • 2021-09-24
    • 2021-06-14
    相关资源
    最近更新 更多