vuex

头像
清儿
    阅读 5 分钟
    1

    项目目录结构

    clipboard.png
    clipboard.png

    main.js

    import Vue from 'vue'
    import axios from 'axios'
    import app from './app'
    
    import router from './route'
    import store from './store'
    
    import 'ui'
    
    // 为axios配置的请求拦截
    axios.interceptors.request.use(function (req) {
      if (req.method === 'get') {
        if (req.url.indexOf('?') === -1) {
          req.url += '?'
        } else {
          req.url += '&'
        }
        // 在每一次请求的后边加上一个参数,请求的时间为当前时间
        req.url += 'requesttime=' + new Date().getTime()
      }
      return req
    })
     // 为axios配置的响应拦截
    axios.interceptors.response.use(function (res) {
      res = res.data
      if (res.success) {
        return res.data
      } else {
        if (res.message) {
          store.state.noticeBus.$emit('fail', res.message)
        }
        return Promise.reject(res.remark ? {message: res.message, remark: res.remark} : res.message)
      }
    }, function (err) {
      console.log(err)
      store.state.noticeBus.$emit('fail', '网络错误')
      return Promise.reject('网络错误')
    })
    
    router.beforeEach((to, from, next) => {
      if (window.__alphaUserData__) {
        store.commit('SET_USER_DATA', window.__alphaUserData__)
        document.getElementById('__alphaUserData__').remove()
        window.__alphaUserData__ = null
        next()
      } else {
        // next()
        store.dispatch('GET_USER_DATA', ((to.path === '/' ? '/index' : to.path) + '.json')).then(res => {
          store.commit('SET_USER_DATA', res)
          next()
        }, err => {
          console.log(err)
          window.location.reload()
        })
      }
    })
    
    router.afterEach(() => {
      store.commit('NAV_HIDE_LIST')
      store.commit('SET_ACTIVE_ADD', '_af_inactive')
    })
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      store,
      render: h => h(app)
    })
    

    父级store/index.js

    mport Vue from 'vue'
    import Vuex from 'vuex'
    import axios from 'axios'
    import qs from 'qs'
    import projectStore from '../page/project/store'
    import talentStore from '../page/talent/store'
    import posexec from '../page/posexec/store'
    import order from '../page/order/store'
    import workbench from '../page/workbench/store'
    import positionStore from '../page/position-manager/store'
    Vue.use(Vuex)
    
    const state = {
        userData: {}
    }
    const getters = {
      userId: state => state.userData && state.userData.user && state.userData.user.userId
    }
    const mutations = {
        SET_USER_DATA (state, data) {
            state.userData = data
        }
    }
    const actions = {
        // get
        GET_SALARY ({state, commit}, user) {
            return axios.get(`/api/usermanager/getIntention/${user}`).then(res => {
              commit('SET_SALARY', res)
            }, err => {
              console.log(err)
            })
        },
        GET_MATCHED_COMPANY_LIST (ctx, params) {
            return axios.get('/api/positions/list/clientAutoComplete', {params})
        },
        // post
        ADD_CHAT_RECORD (ctx, data) {
            return axios.post('/api/position/manager/appendChatRecord.json', qs.stringify(data))
        },
          CHANGE_SALARY (ctx, data) {
            return axios.post(`/api/usermanager/setIntention/${data.commonUserId}`, data.condition).then(res => {
              console.log(res)
            }, err => {
              console.log(err)
            })
          },
    }
    export default new Vuex.Store({
      state,
      getters,
      mutations,
      actions,
      modules: {
        projectStore,
        talentStore,
        posexec,
        order,
        workbench,
        positionStore
      }
    })

    route/index.js

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    
    import project from '../page/project/route'
    import posexec from '../page/posexec/route'
    import talent from '../page/talent/route'
    import order from '../page/order/route'
    import positionManager from '../page/position-manager/route'
    
    import demo from '../lib/demo/route'
    
    Vue.use(VueRouter)
    
    const router = new VueRouter({
      routes: [project, posexec, talent, order, positionManager, demo],
      // scrollBehavior意思是在跳转到新的路由时可以到了页面的顶部,只适用于在HTML5的history模式下
      scrollBehavior (to, from) {
        return {x: 0, y: 0}
      },
      // vue-router使用history模式,主要是用了HTML5中的pushState.vue中路由默认的事hash模式
      mode: 'history'
    })
    
    export default router

    子级page/project/store/index.js

    import axios from 'axios'
    import qs from 'qs'
    
    const state = {}
    
    const getters = {}
    const mutations = {}
    const actions = {
        POSITION_GROUP (ctx, payload) {
            return axios.get('/api/positions/group/statistics/dropDownList', {
              params: payload
            })
        }
    }
    export default {
      state,
      getters,
      mutations,
      actions
    }

    组件内调用action

    methods: {
        searchPosition () {
          const searchKey = this.searchPositionRelevance
          const resultArr = []
          this.$store.dispatch('POSITION_GROUP', searchKey).then(res => {
            res.forEach(item => {
              if (item.name.includes(searchKey)) {
                resultArr.push(item)
              }
            })
          }, err => {
            console.log(err)
          })
          this.relevanceListDate = resultArr
        }
    }

    清儿
    72 声望0 粉丝