Vuex状态变量被删除

时间:2018-11-15 18:01:03

标签: vue.js vuex

TLDR:为什么store变量在一个js文件中导入4个VUEX变量,而在另一个js文件中导入2个VUEX变量?

我有一个很奇怪的问题,我已经坚持了一段时间。我们的站点有4个Vuex状态变量(导航,selectedStore,uri和feature)。我导入商店以将其放置在index.js文件的顶部。没有导入,我将在站点上的Vue开发工具中显示所有4个Vuex变量。一旦添加了该导入行,其中的2个就会消失(uri和feature都消失了)。但是我需要导入才能获取我的商店变量。所以我很困惑。如果没有该导入并且在Vue实例中包含store,则在控制台中会出现以下错误:[Vue warn]: Error in mounted hook: "TypeError: this.$store is undefined"

index.js

import ProductSlider from '../../components/slider/ProductRecommendationsSlider'
import Vue from 'vue';
import VueCarousel from 'vue-carousel';
import Vuex from 'vuex';
import store from '../modules/global-state'; // this is the culprit line
import global from '../modules/util/global';

Vue.use(Vuex);
Vue.use(VueCarousel);

Vue.prototype.$store = Vue.prototype.$store || store;

global.qubitProductDetailsRecommendationsVue=function(compositeModelNumbers) {
    var params = {
      compositeModelNumbers: compositeModelNumbers,
      strategy: 'pp1',
      backupStrategy: 'popular',
      divId: 'recommendedProductsDetailsHorizontal',
      isVertical: false,
      isHideHeaderText: false,
      headerText: 'Guests Who Viewed This Item Also Viewed These',
      backupHeaderText: 'Popular Products',
      itemsPerPage: 5,
      itemDisplayLimit: 10,
      numberOfItems: 15,
      qubitResponseMap: null
    };

  /* eslint-disable no-new */
  new Vue({
    el: '#recommendedProductsDetailsHorizontal',
    store,
    components: {ProductSlider},
    data: { params },
    template: '<product-slider/>'
  });
};

ProductRecommendationsSlider.vue

<script>
  import Slider from './Slider'
  import {mapState} from 'vuex'
  //import axios from 'axios';

  export default {
    name: "Slider",
    components: {
      Slider
    },
    props: {
      numSlides: {
        type: Number,
        default: 5
      },
      itemsPerPageCssStyle: {
        type: String,
        default: "slider5buckets" // need to eventually make this dynamic, logic is in GridDynamic_DynamicProductRecs.java on lines 125-130
      }
    },
    data: function () {
      return {
        products: [
          {id: 1, img: 'https://placeimg.com/100/100', price: 4.56},
          {id: 2, img: 'https://placeimg.com/101/101', price: 1.23},
          {id: 3, img: 'https://placeimg.com/102/102', price: 2.34},
          {id: 4, img: 'https://placeimg.com/103/103', price: 9.87},
          {id: 5, img: 'https://placeimg.com/104/104', price: 3.45},
          {id: 6, img: 'https://placeimg.com/105/105', price: 12.34},
        ],
        params: this.$parent.params
      }
    },
    computed: {
      ...mapState({
        selStoreID: state => state.selectedStoreId,
        //baseUri: state => state.uri.application || '/main/',
        serviceHost: state => state.uri.service
      }),
    },
    mounted() {
      console.log('strategy: ' + this.params.strategy);
      this.initSlider();
    },
    methods: {
      initSlider () {
        let vm = this;
        let vmStore = vm.selStoreID;
        console.log(vmStore);
<template>
  <div
    id="recommendedProductsDetailsHorizontal"
    :class="['imageSliderContainer', itemsPerPageCssStyle]"
    style="width:100%;height:374px;">
    <h2>{{ params.headerText }}</h2>
    <div
      class="wrapper"
      style="height:355px;">
      <div class="carousel-view">
        <carousel
          :navigation-enabled="true"
          :min-swipe-distance="1"
          :per-page="5"
          navigation-next-label="<i class='fas fa-angle-right'></i>"
          navigation-prev-label="<i class='fas fa-angle-left'></i>">
          <slide
            v-for="product in products"
            :key="product.id">
            <div class="img-container">
              <a
                href="#"
                class="handCursor"
                tabindex="0">
                <img
                  :src="product.img"
                  :alt="'Product #' + product.id">
              </a>
            </div>
            <h4>Product #{{ product.id }}</h4>
            <div class="price-div">
              <div class="allPriceDescriptionPage">${{ product.price }}</div>
            </div>
            <a
              href="#"
              tabindex="0"
              name="instantadd">
              <div class="btn_CA_Search buttonSearch gradient"> Add to Cart</div>
            </a>
          </slide>
        </carousel>
      </div>
    </div>
  </div>
</template>

global-state / index.js -uri和功能来自return JSON.parse(global.__VUEX_STATE__);

import global from '../util/global';
import navigation from './modules/navigation';
import selectedStore from '../store/selected-store';
import Vue from 'vue';
import Vuex from 'vuex';
import _ from 'lodash';
import '@babel/polyfill';

Vue.use(Vuex);

const defaultState = {
  selectedStore: {}
};

const serverState = (() => {
  try {
    return JSON.parse(global.__VUEX_STATE__);
  } catch (e) {
    return {};
  }
})();

const store = new Vuex.Store({
  state: Object.assign({}, defaultState, serverState),
  modules: {
    navigation
  },
  getters: {
    selectedStoreId: state => {
      let store = state.selectedStore;
      if (_.isEmpty(store) || _.isEmpty(store.address)) {
        return 3598;
      }
      return store.id;
    }
  },
  mutations: {
    setSelectedStore(state, payload) {
      if (_.isFinite(payload)) {
        selectedStore.set(payload).then(result => state.selectedStore = result);
      } else {
        state.selectedStore = payload;
      }
    }
  },
  actions: {
    fetchSelectedStore({commit, state}) {
      return new Promise((resolve) => {
        if (!_.isEmpty(state.selectedStore)) {
          resolve();
        }

        selectedStore.get(false).then(store => {
          commit('setSelectedStore', store);
          resolve();
        });
      });
    }
  }
});

store.dispatch('fetchSelectedStore');
store.dispatch('navigation/fetchQuickLinks');

export default store;

更新:-添加更多信息以防万一。这是用于不同组件的不同index.js文件。 index.js中的store变量确实包含所有4个Vuex变量。我不知道有什么区别。

index.js

import Header from '../../components/header/Header';
import Vue from 'vue';
import axios from 'axios';
import store from '../modules/global-state';
import '@babel/polyfill';

Vue.prototype.$http = Vue.prototype.$http || axios;
Vue.prototype.$store = Vue.prototype.$store || store;

/* eslint-disable no-new */
new Vue({
  el: '#header',
  components: {Header},
  template: '<header/>'
});

0 个答案:

没有答案
相关问题