vuex
import { inject, reactive, computed } from 'vue'
const STORE_KEY = 'store-key'
const useStore = ( ) => {
return inject ( STORE_KEY )
}
const createStore = ( opts ) => {
return new store ( opts)
}
class store {
constructor ( opts ) {
this . $store_opts = opts
this . $my_store = reactive ( {
data : opts. state ( )
} )
this . $store_mutations = opts. mutations
this . $store_actions = opts. actions
this . getters = new Proxy (
{ } ,
{
get : function ( target, property ) {
return target[ property] . value
}
}
)
if ( opts. getters) {
Object. keys ( opts. getters) . map ( ( key ) => {
const func = opts. getters[ key]
this . getters[ key] = computed ( ( ) => func ( this . state) )
} )
}
}
get state ( ) {
return this . $my_store. data
}
commit = ( type, payload ) => {
const func = this . $store_mutations[ type]
if ( ! func) {
console. warn ( 'store actions is not' , type)
return func
} else {
func ( this . state, payload)
}
}
dispatch = ( type, payload ) => {
const func = this . $store_actions[ type]
if ( ! func) {
console. warn ( 'commit mutations is not' , type)
return undefined
} else {
return func ( this , payload)
}
}
install = ( app ) => {
app. provide ( STORE_KEY , this )
}
}
export { createStore, useStore }
创建store 仓库
import { createStore } from './myVuex'
const store = createStore ( {
state : ( ) => {
return {
num : 1 ,
info : {
name : '' ,
age : ''
}
}
} ,
mutations : {
setNum ( state, data ) {
state. num = data
} ,
setInfo ( state, data ) {
state. info = data
}
} ,
actions : {
async getInfo ( { commit } ) {
setTimeout ( ( ) => {
commit ( 'setInfo' , {
name : '嘿嘿嘿' ,
age : 18
} )
} , 1000 )
}
} ,
getters : {
double ( state ) {
return state. num * 2
}
}
} )
export default store
vue注册
import myVuex from './vuex/index'
const app = createApp ( App)
app. use ( myVuex)
app. mount ( '#app' )
测试代码
import { useStore } from '../../vuex/myVuex'
const store = useStore ( )
const storeState = computed ( ( ) => store. state)
console. log ( storeState. value)
store. commit ( 'setNum' , 43 )
console. log ( storeState. value, '2' )
const getInfo = async ( ) => {
await store. dispatch ( 'getInfo' )
console. log ( storeState. value, '2' )
}
getInfo ( )
const num2 = computed ( ( ) => store. getters. double)
console. log ( num2. value, 'num * 2' )