gpt4 book ai didi

javascript - Vuex Store 访问状态为 'this'

转载 作者:行者123 更新时间:2023-12-01 16:16:19 25 4
gpt4 key购买 nike

我目前正在学习 Vuex 和阅读 this Vue 官方文档的一部分。我想知道是否有特殊原因我们会使用参数访问 state 而不是仅仅使用 this?我测试了事情是否适用于它所做的 this

Vue 示例

const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
state.count++
}
}
})

我的例子

const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment () {
this.count++;
}
}
})

最佳答案

Vuex store 实例不是一个拥有自己的 this 的普通对象,它可以被看作是提供一些输入/输出的黑盒子,它将状态作为参数传递,然后在其内部逻辑(模式)根据您的突变更新状态,对于 this available here:

 mutations: {
increment () {
this.count++;
}
}

它指的是全局window对象。

根据@Spinx 的评论,this 指的是版本 3 及更高版本中的 vuex 实例,我发现 @Matt 所说的是一个很好的说明:

IMO this is a great example of why you should use the explicit parameter since you don't know how your function is bound __Matt

关于javascript - Vuex Store 访问状态为 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63748036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com