在创建VueJS应用之前如何加载数据?

时间:2018-11-16 13:47:03

标签: vue.js

我有点困惑。如何加载数据(main.js文件)和afrer(组件内部)将此数据设置为data()函数(calc.js)?

我有data.json文件:

{
    "store_data": "VUE_STORE",
}

我有store.js

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

export const store = new Vuex.Store({

    state: {
        url_server: 'data.json',
        store_data: '',
    },
    actions: {
        getServerData({commit}){

            return new Promise((resolve, reject) => {

                Vue.http.get(this.state.url_server).then(function (response) {
                    if (response.status == "200") {
                        commit('LOAD_SERVER_DATA', response)
                        resolve()
                    }
                });

            });

        }

    },

    mutations: {
        LOAD_SERVER_DATA (state, response) {
            this.store_data = response.data.store_data;
        },
    },

});

我有main.js文件:

import Vue from 'vue';
import VueResource from 'vue-resource';
import { store } from './store/store';
Vue.config.productionTip = false;
import calc from './components/calc/calc';

Vue.use(VueResource);

var app = new Vue({
    el: '#app',
    store,
    data: {},
    components: {
        'calc': calc,
    },
    beforeCreate() {
        this.$store.dispatch('getServerData');
    }
});

以及组件文件calc.js

module.exports = {
    name: 'calc',
    template: `
        <div>
            <h1>calc</h1>
            <h2>{{test_value}}</h2>
        </div>
    `,
    data() {
        return {
            test_value: 'AAA',
        }
    },
    methods: {
        updateTimer() {
        },
    },
    created() {
        this.test_value = this.$store.state.store_data;
/*        this.$store.dispatch('getServerData').then(() => {
            this.test_value = this.$store.state.store_data;
            console.log(this.$store.state.store_data);
        });*/
    },
    computed: {

    },
    mounted() {

    },

};

我想在calc.js文件值this。$ store.state.store_data中设置一个test_value。怎么可能?

1 个答案:

答案 0 :(得分:1)

请勿将数据用于商店拥有的数据。使用计算返回存储值,就像这样

created() {
    this.$store.dispatch('getServerData');
},
computed: {
    test_value(){
        return this.$store.state.store_data;
    }
},
mounted() {

},

然后在vuex存储区中,该突变存在一个小错误

mutations: {
    LOAD_SERVER_DATA (state, response) {
        state.store_data = response.data.store_data;
    },