使用pinia
// stores/counter.js中
// ref就是state,computed就是getter,函数就是action,没有mutation了
import {ref,} from 'vue'
import {defineStore} from 'pinia'
export const useCounterStore = defineStore('counter', () =>{
const ount = ref(0)
const doubleCount = computed(() => {count.value * 2})
function increment() {
count.value++
}
return {count, doubleCount, increment}
})
// vue文件中
<script setup>
import {useCounterStore} from '../stores/counter'
const countStore = useCounterStore()
</script>
使用vuex
全景
// Store实例属性
state(根状态,只读) getters(只读)
// Store实例方法
commit、dispatch、replaceState、watch、registerModule、hasModule
// 辅助函数(mapState、mapGetters、mapActions、mapMutations)
同一个辅助函数可以在同一个组件多次调用,方便在组件中同时获取局部内容和全局内容
辅助函数的返回值都是对象,所以可以使用展开运算符
module
const store = createStore({
modules: {
account: moduleA,
xxx: moduleB
}
})
const moduleA = {
namespaced: true,
state: () => ({ msg: '' }), // -> store.account.msg
getters: {
isAdmin () { ... } // -> getters['account/isAdmin']
},
actions: {
login () { ... } // -> dispatch('account/login') ...mapActions('account',[login])
},
mutations: {
login () { ... } // -> commit('account/login') ...mapMutations('account',[login])
},
}
const moduleB = {
namespaced: true,
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
state
- 定义
state = {
count: 0,
}
- 使用
store.state.count
computed:{
...mapState(['aa','bb']) // this.aa
}
getter
- 定义
getters: {
//接受如下参数
//state,
//getters,
//rootState,//只在模块中出现
//rootGetters,//只在模块中出现
doneTodos(state){
return state.todos.filter(todo => todo.done)
}
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
- 使用
store.getters.doneTodos
store.getters.getTodoById(2)
computed:{
...mapState(['doneTodos','getTodoById']) // this.getTodoById
}
mutation
改变状态的唯一途径
- 定义
mutations: {
//处理函数的第一个参数:state(如果定义在模块中,则为模块的局部状态)
//处理函数的第二个参数(可选):payload
increment (state, payload) {
state.count+= payload
}
}
- 使用
store.commit('increment',{amount: 10})
methods: {
...mapMutation(['increment']) this.increment
}
action
不可直接改变状态,用来包含异步操作
- 定义
// action的处理函数返回的是promise
actions: {
// context对象包含一下属性:
// state,相当于store.state,在模块中为局部状态
// rootState,只存在于模块当中
// commit,相当于store.commit
// dispatch,相当于store.dispatch
// getters,相当于store.getters
// rootGetters,//只存在于模块当中
increment (context, payload) {
context.commit('increment', payload)
},
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
- 使用
store.dispatch('incrementAsync', {amount: 10})
methods: {
...mapMutation(['increment']) this.increment
}