【问题标题】:Can I use this in Vuex store?我可以在 Vuex 商店中使用它吗?
【发布时间】:2020-10-13 08:57:44
【问题描述】:

我使用 vue-cookiesvue-resource 创建项目,我尝试使用 this.$cookies.get('my-cookie') 访问 cookie 并使用 this.$http.post('URL') 请求我的 API。啧啧商店无法访问this

我在 store.js 中的操作:

checkCookies: () => {
    if (this.$cookies.get('test') === null) {
        console.log('vide')
        //envoyer sur la page de connexion
    } else {
        console.log('pas vide')
        this.$http.post('URL', {

        })
    }
}

我如何调用我的操作(点击时调用方法):

test() {
        return this.$store.dispatch('checkCookies')
      }

我的测试函数是如何被调用的:

<v-btn @click="test">cookies!</v-btn>

当我运行checkCookies 时出现此错误:

v-on 处理程序中的错误:“TypeError: _this is undefined”

我通常会在我的商店中使用this,我知道我可以一个一个地导入每个包来使用它们,但是我想知道是否有办法在 vuex 中使用this 到?

【问题讨论】:

  • 请提供minimal reproducible example。你得到什么错误?
  • 你想用这个(vuex 商店的上下文)来访问那个(Vue 实例的上下文)?
  • 是的,我想在 vuex 商店中保留上下文
  • 没有箭头功能,可能我用的时候 this.$store.dipsatch('myAction') 忽略上下文

标签: javascript vuejs2 vuex vue-resource vue-cookies


【解决方案1】:

this.$cookiesthis.$http 在组件方法中工作,因为这些函数是由它们各自的插件添加到 Vue.prototype 的。

无论如何,这些只是方便的方法;似乎这些插件直接在Vue 上安装了等效方法:

this.$http    -> Vue.http
this.$cookies -> Vue.$cookies

如果您真的希望能够在 Vuex 操作中执行 this.$http,那么您需要将方法分配给商店:

const store = new Vuex.Store({ ... })

// Make sure you have registered the Vue plugins by this point
store.$http = Vue.http
store.$cookies = Vue.$cookies

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-22
    • 2021-07-22
    • 2017-12-18
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多