Vue变量无法在Vuex中访问

时间:2017-09-15 07:56:06

标签: javascript vuejs2 vuex

我在$shopifyClient中定义了一个名为Vue的变量,该变量在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 个答案:

答案 0 :(得分:1)

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

//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;