vuex中的actions 处理异步数据请求,然后通过mutations设置state中的变量值,返回到每个组件中并展示出来。
1-改造03例子中的vuex,代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
curIdx: 0,
name: '李一就',
age: 35,
data: []
},
mutations: {
setIdx(state, index) {
state.curIdx = index;
},
setData(state, data) {
state.data = data;
}
},
getters: {
getMyInfo(state) {
return "我的名字叫" + state.name + " , 今年有" + state.age + "岁了。"
}
},
actions: {
getData(ctx, payLoad) {
return new Promise(async(resolve, reject) => {
const res = await axios.post('http://127.0.0.1:9200/layerinfo/_search', payLoad);
ctx.commit('setData', res.data);
resolve();
})
}
},
modules: {}
})
2-新建展示数据的组件part,代码如下:
<template>
<div>
<table>
<thead>
<td>名称</td>
<td>类型名称</td>
<td>数据集</td>
</thead>
<tbody>
<tr v-for="(row,index) in data" :key= "index">
<td>{{row.name}}</td>
<td>{{row.dataclass}}</td>
<td>{{row.datasetcn}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
// 这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
export default {
components: {
},
// 定义属性
data() {
return {
data:[]
}
},
created () {
var that = this;
const payload ={
"from":0,
"size":492,
"_source":["dataclass","datasetcn","name"]
};
this.$store.dispatch('getData', payload).then(function(res){
const mdata = that.$store.state.data.hits.hits;
for (let index = 0; index < mdata.length; index++) {
const element = mdata[index]['_source'];
that.data.push(element);
}
})
},
methods: {
},
// 生命周期 - 挂载完成(可以访问DOM元素)
mounted() {
}
}
</script>
<style scoped>
table{
border: 1px solid #cccccc
}
thead {
font-size: 16px;
font-weight: bold;
}
table td{
border-right: 1px solid #cccccc;
border-bottom: 1px solid #cccccc;
text-align: left;
width: 200px;
height: 40px;
}
</style>
3-效果如下: