首页 > 解决方案 > 如何在创建 VueJS 应用程序之前加载数据?

问题描述

我有点困惑。如何加载数据(main.js 文件)并进一步(在组件内)将此数据设置为 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。怎么可能?

标签: vue.js

解决方案


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

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;
    },

推荐阅读