. 下载安装 cnpm install vuex -S ;本次下载的版本是 "vuex": "^4.0.2"
2.创建store/index.js
import { createStore } from 'vuex'
import http from '@/utils/http.js'
// Create a new store instance.
const store = createStore({
state () {
return {
count: 0,
user:{}
}
},
mutations: {
increment (state,num) {
state.count += num;
},
setUser(state,user){
state.user = user;
}
},
actions:{
getUserInfo(context,params){
return new Promise((resolve,reject)=>{
http.get("/pyapi/test/user",params).then(res=>{
if(res.status == 200){
context.commit("setUser",res.result)
resolve(res.result)
}else{
reject({})
}
}).catch(e=>{
reject(e)
})
})
}
}
})
export default store
3. 在main.js中
import store from './store/index.js'
const App = createApp(App)
app.use(store)
4.在组件中使用
<template>
<div class="test">
<p>count:{{ count }} <el-button @click="addCount">+2</el-button></p>
</div>
<div class="user">
<el-button @click="getUserInfo">getUserInfo</el-button>
<ul>
<li>name: {{user.name}}</li>
<li>age: {{user.age}}</li>
</ul>
</div>
</template>
<script>
import $store from '@/store/index.js'
import { computed } from 'vue';
export default {
name: "testCom",
setup() {
let count = computed(()=>{
return $store.state.count
})
const addCount = ()=>{
$store.commit('increment',2) // 同步
}
let user = computed(()=>{
return $store.state.user
})
const getUserInfo = ()=>{
$store.dispatch('getUserInfo', {id:111}); // 异步
}
return {
count,
addCount,
user,
getUserInfo
};
},
};
</script>
<style scoped>
</style>