You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue . use ( Vuex )
const state = {
listA : [ ] ,
listB : [ ]
}
const requestMap = {
listA : ( state ) => {
setTimeout ( ( ) => {
state . listA = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
} , 3000 )
} ,
listB : ( state ) => {
setTimeout ( ( ) => {
console . log ( 'request B' )
state . listB = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
} , 1000 )
}
}
Object . keys ( state ) . forEach ( key => {
// 处理vue初始化get导致提前执行函数
let vueInitCount = 0
const defaultValue = state [ key ]
// 避免循环调用, 当获取listA, 实际上返回的是__listA
// 设置listA, 实际设置的是__listA
const privateKey = ` __ ${ key } `
Object . defineProperty ( state , key , {
get ( ) {
if ( vueInitCount < 2 ) {
vueInitCount ++
return defaultValue
}
if ( ! this [ privateKey ] || ( Array . isArray ( this [ privateKey ] ) && this [ privateKey ] . length === 0 ) ) {
const fun = requestMap [ key ]
if ( fun ) {
fun ( state )
}
}
return this [ privateKey ] || defaultValue
} ,
set ( val ) {
this [ privateKey ] = val
}
} )
} )
export default new Vuex . Store ( {
state ,
} )