gpt4 book ai didi

javascript - Vue 变量在 Vuex 中无法访问

转载 作者:行者123 更新时间:2023-12-03 03:27:56 26 4
gpt4 key购买 nike

我在 Vue 中定义了一个名为 $shopifyClient 的变量,该变量在 Vuex 中无法访问。我如何使这个变量可访问?

Vue.$shopifyClient.addLineItems('1234', lineItems).then((checkout) => {
console.log(checkout.lineItems)
})

返回TypeError:无法读取未定义的属性“addLineItems”,因此我假设它无法检索$shopifyClient

main.js

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.prototype.$shopifyClient = new Client(
new Config({
domain: 'some-page.myshopify.com',
storefrontAccessToken: '123456'
})
)

/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
template: '<App/>',
components: { App }
})

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
export default new Vuex.Store({
state: {
lineItems: { }
},
actions: {
addToCart ({ commit, state }) {
var lineItems = [{variantId: '12345==', quantity: 2}]
Vue.$shopifyClient.addLineItems('1234', lineItems).then((checkout) => {
console.log(checkout.lineItems)
})
}
}
})

最佳答案

您可以在Vuex存储中声明$shopifyClient,如下所示:

//Store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
export default new Vuex.Store({
state: {
lineItems: { },
$shopifyClient: new Client(
new Config({
domain: 'some-page.myshopify.com',
storefrontAccessToken: '123456'
})
)
},
actions: {
addToCart ({ commit, state }) {
var lineItems = [{variantId: '12345==', quantity: 2}]
state.$shopifyClient.addLineItems('1234', lineItems).then((checkout) => {
console.log(checkout.lineItems)
})
}
}
})


// vue component
//you can access it like below

this.$root.$store.state.$shopifyClient;

关于javascript - Vue 变量在 Vuex 中无法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46234540/

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