首页 文章

Vue变量无法在Vuex中访问

提问于
浏览
0

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

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

返回 TypeError: Cannot read property 'addLineItems' of undefined ,所以我认为它无法检索 $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)
      })
    }
  }
})

1 回答

  • 1

    您可以在 Vuex store中声明 $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;
    

相关问题