pinia 是vuex的简化版,兼容vue2和vue3
基本使用如下:
- 下载:yarn add pinia@next 或者 npm install pinia@next
- 创建store仓库:
// store/index.ts
import { defineStore } from 'pinia';
type stateType = {
name: String,
type: String,
dataList: String[]
}
export const piniaStore = defineStore('main', {
state: ():stateType => ({
name: '玛丽',
type: 'admin',
userList: []
}),
getters: {
getName: state => state.name
},
actions: {
async addNameDelay(data:String) {
console.log('stoewadd--',data)
await new Promise((reslove,reject) => {
setTimeout(() => {
console.log('延迟一秒')
this.userList.push(data)
reslove('ok');
}, 1000)
})
}
}
})
- 在main.ts文件使用
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App)
.use(router)
.use(createPinia())
.mount('#app')
- 在组件中使用
// 引入store和映射方法
import {piniaStore} from '@/store/pinia'
import {mapActions, mapState} from 'pinia'
export default defineComponent({
name: 'uList',
data () {
return {
dataList: [],
store: '',
searchKey: '',
add: {}
}
},
computed: {
...mapState(piniaStore, ['name', 'getName']), // state 和getters都使用mapState映射获取
},
methods: {
...mapActions(piniaStore, ['addNameDelay']) // 使用mapActions获取actions方法
},
mounted() {
/**state, getters,actions 都可以通过store直接点出来 **/
// const store = piniaStore();
// console.log('获取state里面的name ===', store.name)
// console.log('获取getters里面的getName===', store.getName)
// console.log('调用actions里面的方法 ===', store.addNameDelay('ssf'))
},
...
官方文档:https://pinia.vuejs.org/