Skip to main content

Pinia 和 Vuex

Pinia:

State、Gettes、Actions(同步异步都支持)

Vuex

Vuex: State、Gettes、Mutations(同步)、Actions(异步)

import { createStore } from 'vuex'

const state = {
test:''
}
// mutations通常为修改state数据而使用,这用就可以避免直接修改state的数据
const mutations = {
changeData(state,val){
state.test = val
}
}

// actions当你的数据是需要发送请求获取时,这是非常完美的选择
const actions = {
async fetchData(context,payload){
const res = await getData(payload)
context.commit('changeData',res.data)
}
}

// getters用来处理数据,对state中的数据进行处理,得到自己想要的效果
const getters = {
getData(state){
return state.test
}
}

const store = createStore({
actions,
mutations,
state
})

export default store


// 挂载
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import store from './store'
const app = createApp(App)
app.use(store)
app.mount('#app')


// 组件内使用action
import { useStore } from "vuex";
export default {
setup() {
const store = useStore();
async function foo() {
await store.dispatch("fetchData", {
id: 123,
});
}

return {foo}
},
};

// mutations 使用
import { useStore } from "vuex";
export default {
setup() {
const store = useStore();
store.commit('changeGoods',123)
},
};

// 获取state
import { useStore } from "vuex";
export default {
setup() {
const store = useStore();
console.log(store.state.test);
},
};

// getters
import { useStore } from "vuex";
export default {
setup() {
const store = useStore();
console.log(store.getters['getData']);
},
};