仓库模板
//引入api
import { } from '@/api';
// 仓库存储数据
const state ={};
// 修改state的唯一手段
const mutations ={};
// 处理action,可以书写自己的业务逻辑,也可以处理异步
const actions ={};
// 计算属性,用于简化仓库数据,让组件获取仓库数据更加方便
const getters ={};
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 引入小仓库
import home from './home'
export default new Vuex.Store({
// 实现Vuex仓库模块式开发存储数据
modules:{
home
}
})
api.js
export const getBanner = ()=>requests({url:'/index/getBanner',method:'get'})
仓库存储
import {getBanner} from '@/api';
const state={
bannerList:[]
};
const mutations={
BANNERLIST(state,bannerList){
state.bannerList = bannerList;
}
};
const actions={
// 获取轮播图数据
async bannerList({commit}){
let result = await getBanner();
if(result.data.code == 0){
commit("BANNERLIST",result.data.data)
}
console.log(result.data)
}
};
const getters={};
export default {
state,
mutations,
actions,
getters
}
获取仓库数据
<script>
import { mapState } from "vuex";
export default {
name: "Banner",
data() {
return {
};
},
mounted() {
this.$store.dispatch("bannerList");
},
methods: {
},
computed: {
...mapState({
bannerList: (state) => state.home.bannerList,
}),
},
};
</script>