vue.js - 如何在创建 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。怎么可能?
解决方案
不要将数据用于商店拥有的数据。使用计算返回存储值,像这样
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;
},
推荐阅读
- python - 使用python从xml文件中读取和解析值
- c# - 如何确定子类或 GrandChild 类是否需要 TenantId?
- c# - 我的 excel 正在编写时遇到问题,我无法停止执行
- ios - 实现twilio语音呼出,什么是“语音机器人”?
- javascript - 代码沙盒 - /src/index.js 执行两次
- node.js - 如何使用 ngx-cookie 读取 PassportJS 会话 cookie?
- c# - 我在二维数组中给出错误的结果
- python - 如何将过滤器应用于局部最大值(绘图)
- firebase - Firebase 身份验证电子邮件链接无密码 - 我是否必须制作自己的服务器端应用程序来处理身份验证
- java - 如何使用冒泡排序对人进行排序?