vuex

項目目錄結構

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
    }
}
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息