标签:const state pinia vue3 import vuex store
前言
vue3中使用了全新的组合式API: https://v3.cn.vuejs.org/
vuex从4.x版本开始也对应的提供了适配vue3的api:https://vuex.vuejs.org/zh/
pinia是新出现的状态管理工具,相对于vuex更加精简: https://pinia.vuejs.org/
pinia
注意:
- pinia 合并了 mutation 和 action,包括异步
- 无需通过mutation修改state,store.count++可以直接修改状态
// 导入pinia
import { createPinia } from 'pinia';
const pinia = createPinia();
let app = createApp(App);
app.use(pinia);
// 正文,主模块
import { defineStore } from 'pinia';
const useMainStore = defineStore('main', {
state: () => {
return {
test: null,
}
},
actions: {
changeTest() {
},
async getTest() {
// await
}
},
getters: {
}
})
// 其他模块
const useChildStore = defineStore('child', {
state: () => {
return {
testChild: null,
}
},
actions: {
changeTestChild() {
},
async getTestChild() {
// await
}
},
getters: {
}
})
// 使用
import { useMainStore } from '@/store';
const store = useMainStore();
store.setLang(lang); // store.lang = lange;
const { lang } = toRefs(store);
vuex
注意:
- mutations中必须是同步函数
- Action 类似于 mutation,区别是action提交mutation,且action可以异步
// 导入vuex
import { createApp } from 'vue';
import store from '@/store';
app = createApp(App);
app.use(store);
// 正文
const store = createStore({
state: {
count: 1,
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos (state) {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
increment (state, payload) {
state.count += payload.amount; // store.commit('increment', {amount: 10})
}
},
actions: {
increment (context) {
context.commit('increment'); // store.dispatch('increment')
},
async actionB ({ dispatch, commit }, { param }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
},
modules: {
child: childModule,
}
})
// 子模块
const childModule = createStore({
// 命名空间,防止同名时出错
namespaced: true,
state: initialState,
mutations,
actions,
getters,
})
// 使用
import store from '@/store';
store.commit('setLang', lang);
// 使用2
import { useStore } from 'vuex';
const store = useStore();
const { lang } = toRefs(store.state);
标签:const,state,pinia,vue3,import,vuex,store 来源: https://www.cnblogs.com/nangezi/p/16437877.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。