1.创建目录文件
首先通过命令新建脚手架,在src目录下新建store文件夹。并创建index.js入口和modules文件夹(因为我把模块拆分了)
2.store/index.js文件
import { createStore, createLogger } from 'vuex'
import home from './modules/home'
import dome2 from './modules/dome2'
const debug = process.env.NODE_ENV !== 'production'
export default createStore({
modules: {
home,
dome2
},
strict: debug,
plugins: debug ? [createLogger()] : []
})
3.home.js文件,一个独立的模块
import {getErshoufang} from '../../api/home';
const state = () => ({
ershoufang:{},
ResblockInfo:{},
rent:{},
overseas:{}
})
// getters
const getters = {
}
// mutations
const mutations = {
setErshoufang (state,payload) {
state.ershoufang = payload;
},
}
// actions
const actions = {
async getErshou({ commit, state }){
try{
let {data} = await getErshoufang();
commit('setErshoufang',data);
}catch(e){
console.log(e);
}
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
4.使用store
<script>
import {mapState,mapActions} from 'vuex'
export default {
computed: {
...mapState(['ershoufang']),
},
methods: {
...mapActions({
getErshou:"home/getErshou"
}),
},
created () {
this.getErshou();
}
}
</script>
5.在setup中使用store
<script setup>
import { onMounted, toRaw } from "vue";
import { useStore } from "vuex";
//使用vuex
const store = useStore();
store.dispatch("home/getErshou");
store.dispatch("home/getResblock");
store.dispatch("home/getRents");
store.dispatch("home/getoverseases");
onMounted(() => {
let rent = toRaw(store.state.home);
console.log(rent);
});
</script>