如何在vuex存储中使用JSON数据(无Webpack)

时间:2019-05-10 10:21:33

标签: vue.js vuex

我成功设置了我的第一个vuex存储。 数据数组从存储传递到所需的组件并正确呈现。 现在,我想从JSON文件中获取数据,但无法使其正常工作。 我没有使用Webpack,因为有时我需要在没有这些工具的环境中进行项目。

以下内容在不从JSON文件检索数据的情况下有效:

STORE.JS

Vue.use(Vuex);
const store = new Vuex.Store({
    state: {
        products: [
            { name: "Avocado Zwem Ring", inventory: 47, unit_price: 77, image:"a.jpg", new:true },
            { name: "Danser Skydancer", inventory: 5, unit_price: 45.99, image:"a.jpg", new:true}
        ]
    },
});

SHOP.VUE

<template>
    <comp-products v-bind:products="products"></comp-products>
</template>
<script>
module.exports = {
    components: {
        'comp-products': httpVueLoader('components/comp-products.vue')
    },
    computed:{
        products(){ 
            return this.$store.state.products
        }
    }
}
</script>

我尝试了以下操作,但是它不呈现任何内容,但是也不会返回错误。

STORE.JS

Vue.use(Vuex);
const store = new Vuex.Store({
    state: {
        products: [], 
    },
    mounted() {
        axios
        .get("json/products.json")
        .then(response => {
            this.products = response.data.products;
        })            
    },
});

SHOP.VUE

<template>
    <comp-products v-bind:products="products"></comp-products>
</template>
<script>
module.exports = {
    components: {
        'comp-products': httpVueLoader('components/comp-products.vue')
    },
    computed:{
        products(){ 
            return this.$store.state.products
        }
    }
}
</script>

products.json

{
    "products":[
      {
        "sku":"1",
        "name": "Danser Skydancer",
        "inventory": 5,
        "unit_price": 45.99,
        "image":"a.jpg",
        "new":true
      },
      {
        "sku":"2",
        "name": "Avocado Zwem Ring",
        "inventory": 10,
        "unit_price": 123.75,
        "image":"b.jpg",
        "new":false
      }]
}

我确定json文件的路径和axios的设置是正确的,因为我设法在不使用vuex存储的情况下检索和呈现json数据。

2 个答案:

答案 0 :(得分:1)

要在商店中设置变量,应使用突变。 设置商店后,调用您的api,然后使用结果数据在商店中调用变异。

Vue.use(Vuex);
const store = new Vuex.Store({
    state: {
        products: [], 
    },
    mutations: { //Mutations are like setters
        SET_PRODUCTS: (state, products) => { //capitalization is good-practice for vuex-mutations
            state.products = products;
        }
    }
});

const setProductToStore = () => {

    axios
    .get("json/products.json")
    .then(response => {
        store.commit('SET_PRODUCTS', response.data.products);
    })   
}

setProductToStore();

类似的事情应该起作用。

答案 1 :(得分:0)

也可以像这样简单地导入data.json文件:

class App extends React.PureComponent {

  backPress() {
    this.props.dispatch(NavigationActions.back())
  }
  render() {
    // console.log(this.props.apiNetworkError)
    const {dispatch, navState} = this.props;
    return (
      <View style={{ flex: 1 }}>
      <ExitOnDoubleBack exitableRoutes={['Activities','Dashboard']} nav={navState} backHandler={this.backPress.bind(this)}>
        <AppNavigator
            navigation={{
              dispatch: this.props.dispatch,
              state: this.props.navState,
              addListener: () => {}
            }}
        />
        </ExitOnDoubleBack>
      <NetworkNotifier apiNetworkError={this.props.apiNetworkError} dispatch={dispatch}/>
      <NotificationSetup />
      </View>
    );
  }
}


const AppWithNavigationState = connect(state => ({
  navState: state.navState,
  apiNetworkError: state.NetWorkStatus.apiNetworkError,
}))(App);

const composeEnhancers =
  global.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const enhancer = composeEnhancers(applyMiddleware(thunk, networkErrorMiddleware));

const AppContainer = () =>
  (<View style={{ flexGrow: 1 }}>
    <Provider
        store={createStore(reducer, (initialState = {}), enhancer)}
    >
      <AppWithNavigationState />

    </Provider>
  </View>);