openks / learn-vue

自定义组件文档
https://openks.github.io/learn-vue
0 stars 0 forks source link

20171221_使用vuex解决从服务端获取的键值对问题 #71

Open openks opened 6 years ago

openks commented 6 years ago

有全局都可能通用的二级代码(即由服务端返回的对象数组),可以通过vuex存储二级代码,界面上默认显示code通过过滤器过滤为显示的值 由于需要从服务端获取代码可能会存在界面上先显示code再显示成文字的问题(如先显示1再显示为男)

openks commented 6 years ago

页面显示部分

<template slot-scope="scope">
    {{scope.row[item.key]|codeFilter('codeName',hospitalLevelList)}}
</template>

<script>
import { mapActions, mapState } from 'vuex'
computed: {
    ...mapState({
        hospitalLevelList: state => state.static.hospitalLevelList
    })
},
methods: {
        ...mapActions([
            'getHosptialLevel'
        ]),
},
mounted () {
        this.getHosptialLevel()
}

过滤器部分

// src/utils/filters.js
let codeFilter = (value, key, arr) => {
    let returnObj = ''
    let tmp = arr.filter(function (item) {
        if (item.codeValue === value) {
            return item
        }
    })
    if (tmp.length !== 0) {
        returnObj = tmp[0][key]
    }
    return returnObj
}
export {
    codeFilter
}

vuex部分

// src/store/index.js
import moduleA from './modules/static'
const store = new Vuex.Store({
    modules: {
        static: moduleA
    },
    ....
})
// src/store/modules/static.js
import axios, {setStorage, getStorage} from '../../utils/http'
const state = {
    hospitalLevelList: [] 
}
const mutations = {
    hospitalLevelChange (state, payload) {
        state.hospitalLevelList = payload
    }
}
const actions = {
    getHosptialLevel (context) {
        if (getStorage('hospitalLevelList') === null) {
            axios.post('static/list', {
                    codeType: 'hospitalLevel',
            })
                .then(res => {
                    if (res.code === '20000') {
                        setStorage('hospitalLevelList', res.result.data)
                        context.commit('hospitalLevelChange', res.result.data)
                    } else {
                        console.error('代码失败')
                    }
                })
                .catch(err => {
                    console.error('代码异常', err)
                })
        } else {
            context.commit('hospitalLevelChange', getStorage('hospitalLevelList'))
        }
    }
}
export default {
    state,
    mutations,
    actions
}
// src/utils/http.js
// 本地存储放到工具类里去
function setStorage (key, objValue) {
    window.localStorage.setItem('project-name-'  key, JSON.stringify(objValue))
}
function getStorage (key) {
    return JSON.parse(window.localStorage.getItem('project-name-'  key))
}
export {setStorage, getStorage}
openks commented 6 years ago

上面每添加一个静态代码就要重新再写一个state,mutation,action要改动的地方较多 可以将需要改动的地方作为变量,改动后新增静态代码就只需要改动state及调用方法的参数即可

// src/store/index.js
import axios, {
    setStorage,
    getStorage
} from '@/utils/http'
state: {
    staticCode: {
        idTypeList: [],
        hospitalLevelList: []
    }
},
actions: {
    getStaticCodeAction (context, {
        storageName,
        codeType,
        stateName
    }) {
        if (getStorage(storageName) === null) {
            axios.post('staticCode', {
                body: {
                    codeType: codeType,
                    pageSize: '50',
                    pageNum: '1'
                }
            })
                .then(res => {
                    if (res.data.code === '20000') {
                        setStorage(storageName, res.data.result.data)
                        context.commit('StaticMutation', {
                            stateName,
                            stateText: res.data.result.data
                        })
                    } else {
                        console.error('获取静态代码失败')
                    }
                })
                .catch(err => {
                    console.error('获取静态代码异常', err)
                })
        } else {
            // storage里已经存在
            if (context.state.staticCode[stateName].length === 0) {
                // state里面没有(如页面刷新)则重新提交
                context.commit('StaticMutation', {
                    stateName,
                    stateText: getStorage(storageName)
                })
            } else {
                // state已存在不需做任何处理,直接使用即可
            }
        }
    }
},
mutations: {
    StaticMutation (state, payload) {
        state.staticCode[payload.stateName] = payload.stateText
    },
  }

需要用到二级代码的地方做如下处理

import {mapActions, mapState} from 'vuex'
computed: {
  ...mapState({
      idTypeList: state => state.staticCode.idTypeList,
      hospitalLevelList: state => state.staticCode.hospitalLevelList
  })
},
methods: {
  ...mapActions(['getStaticCodeAction']),
},
mounted:{
  // 在需要的地方调用 不一定要在mounted里调用
  this.getStaticCodeAction({
    storageName: 'idTypeList',
    codeType: 'idType',
    stateName: 'idTypeList'
  })
  this.getStaticCodeAction({
    storageName: 'hospitalLevelList',
    codeType: 'hospitalLevel',
    stateName: 'hospitalLevelList'
  })
}