在做项目中 vue2改造vue3项目时的vuex 发生得一些变化
vue3项目中
先看下 stores.js
import { defineStore } from 'pinia' 引入方法注册方法
import { getListFieldLevel } from '..api/index.js'
export const useScreenStore = defineStore('screen', {
state: () => ({
fieldList: [], 定义
instanceCodeOptions: ['11']
}),
actions: { 通过actions改变state的值
async queryFieldList(vo) {
try {
let data
let res = await getListFieldLevel(vo)
data = res.data
const fieldSelect = (data || []).map((item) => {
let obj = {
...item,
id: getInstanceType('333333')
}
return obj
})
this.fieldList = fieldSelect
return fieldSelect
} catch (err) {
this.fieldList = []
return []
}
},
setInstanceCodeOptions(vo) {
this.instanceCodeOptions = { ...this.instanceCodeOptions, ...vo }
}
}
})
function getInstanceType(item) {
return Number(item)
}
- 外面使用
import { mapState, mapActions } from 'pinia'
import { useScreenStore } from '@/stores/screenStore'
computed: {
...mapState(
useScreenStore,
{instanceCodeOptions: (store) => store.instanceCodeOptions || {} }
),
},
methods: {
...mapActions(useScreenStore, ['setInstanceCodeOptions']),
//useScreenStore 知道是那个store下的方法
open(){
this.setInstanceCodeOptions('444') 直接調用setInstanceCodeOptions方法
console.log(this.instanceCodeOptions)
}
}