天天看點

vue頁面跳轉參數傳遞一.頁面跳轉通過路由帶參數傳遞資料二.使用vuex進行資料傳遞

前段時間項目用vue搭建整個前端頁面,我負責的子產品有個地方在頁面跳轉時得将參數傳遞到下一個頁面,但是由于參數較多,用url帶參數傳遞不是特别好,我嘗試了多種方法想在頁面之間傳遞參數都沒成功,最後想到了vuex,當時又是剛開始學vue對vuex更是了解不多廢了一點時間,好在問題解決了,下面分享我解決問題的代碼,希望對大家有所幫助。

一.頁面跳轉通過路由帶參數傳遞資料

// 1.頁面中的代碼
this.$router.push({
    name: 'generalAdminOrderFlowAdd',
    params: {
      type: 'add',
      templateType: this.orderTemplateType
     }
 })
 // 2.路由中的代碼
 {
   path: ':type/:templateType',
   name: 'generalAdminOrderFlowAdd',
   component:   require('@/components/generalAdmin/order/orderFlow')
}
// 3.擷取頁面中的參數值
 let type = this.$route.params.type
           

二.使用vuex進行資料傳遞

// 1.index.js頁面代碼
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'

Vue.use(Vuex)
const state = {
  order: {} //聲明order對象
}
export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})
           
//2. getters.js頁面的代碼
export default {
 // 聲明擷取order的方法
  getOrder (state) {
    return state.order
  }
}
           
//3. mutation.js頁面的代碼
export default {
//設定order的值
  SET_ORDER (state, order) {
    state.order = order
  }
           
// 4.在頁面中設定調用set方法設定全局order的值
this.$store.commit('SET_ORDER', order)// SET_ORDER為order值的設定方法的方法名

           
// 5.擷取全局的order值
 // 從vuex中擷取order
let template = this.$store.state.order