使用WebPack在多个文件中使用Vuex存储

时间:2018-11-06 16:52:11

标签: javascript vue.js webpack vuejs2 vuex

我正在构建一个Web应用程序,该站点的每个页面中都将包含2个JS文件,一个“ bootstrap.js”文件基本上是该站点每个页面上的全局文件,然后是一个自定义JS每个页面的文件。有时我希望这些文件共享同一个Vuex存储,但是当我在一个页面上触发操作时,它不会在另一页面上反映出来。有谁知道如何在多个页面上共享Vuex存储?

我的示例与我正在构建的购物车有关。我希望“ bootstrap.js”文件使用购物车使用的Vuex存储,因此在每个页面上它都可以显示购物车中有多少物品。然后,在某些单独的页面(例如,产品描述页面)上,我想使用相同的Vuex购物车商店将商品添加到购物车,并将总数反映在“ bootstrap.js”文件中。因此,代码如下所示:

global_store.jsx:

import Vue from 'vue'
import Vuex from 'vuex'
import { doAsync } from '../utils/ajax'

Vue.use(Vuex)

const GET_CART_ASYNC = {
  SUCCESS: 'GET_CART_ASYNC_SUCCESS',
  FAILURE: 'GET_CART_ASYNC_FAILURE',
  PENDING: 'GET_CART_ASYNC_PENDING',
}

export let cartStore = new Vuex.Store({
  state: {
    cart: undefined,
    loading: false,
  },
  mutations: {
    [GET_CART_ASYNC.SUCCESS](state, data) {
      Vue.set(state, 'loading', false)
      Vue.set(state, 'cart', data)
    },
    [GET_CART_ASYNC.FAILURE](state) {
      Vue.set(state, 'loading', false)
      Vue.set(state, 'cart', null)
    },
    [GET_CART_ASYNC.PENDING](state) {
      Vue.set(state, 'loading', true)
      Vue.set(state, 'cart', null)
    }
  },
  actions: {
    manipulateCart(store, action=null) {
      doAsync(store, `/cart/api`, GET_CART_ASYNC, action)
    } 
  }
})

boostrap.jsx:

import Vue from 'vue'
import { mapState } from 'vuex'
import { cartStore } from '../cart/global_store'

cartStoreGlobal.dispatch('manipulateCart')

new Vue({
  el: '#cart_display',
  store: cartStore,
  computed: mapState(['cart']),
  render(h) {
    if(this.cart === null) {
      return
    }
    var num_items = this.cart.map(cart_item => cart_item.quantity).reduce((accumulator, quantity) => accumulator + quantity, 0)
    return (
      <p class="navbar-text pull-right" id="mini-cart">
        <a class="button right" href="/cart">
          <strong>{num_items} items</strong> <span>$0.00</span>
        </a>
      </p>
    )
  }
})

cart.jsx

import Vue from 'vue'
import { mapState } from 'vuex'
import { CartView } from '../cart/cart_view'
import { cartStore } from '../cart/global_store'

// TODO: remove this as its already called in bootstrap.jsx, figure out how to use store singletons with webpack
cartStore.dispatch('manipulateCart')

new Vue({
  el: '#cart',
  store: cartStore,
  computed: mapState(['cart']),
  render(h) {
    return (<CartView 
      cart={this.cart} 
      remove_cb={(photo_id_to_remove) => cartStore.dispatch('manipulateCart', [{action: 'set', photo_id: photo_id_to_remove, quantity: 0}])}
    ></CartView>)
  },
})

因此global_store文件包含商店,并且引导程序和购物车正在导入它。 “ doAsync”的细节不是太重要。我是Vue和Vuex的新手,也许还不完全了解WebPack的工作原理,所以非常感谢您进行澄清和/或帮助使其正常工作!

2 个答案:

答案 0 :(得分:0)

将以下行添加到cart.jsx和boostrap.jsx文件中:

Vue.use(cartStore);

导入后。 祝你好运!

答案 1 :(得分:0)

发布此内容以供后代使用。问题在于文件是分开的,这意味着两个完全独立的文件中有两个单独的存储实例,这就是为什么更新一个文件中的状态不会影响另一个文件的原因。结案了。