Vue项目路由使用

Vue项目有关路由的使用
用一个简单的示例来进行说明

router.js

项目中的路径都写在该文件中

import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/login'
import UserList from '@/views/user/user/userList'
import UserAdd from '@/views/user/user/userAdd'
import UserEdit from '@/views/user/user/userEdit'
import UserDetail from '@/views/user/user/userDetail'
var router = new Router({
    //mode:'history',
    routes: [
        {
            path: '/login',            //映射路径
            name: 'Login',        //页面titie
            component: Login  //组件实际路径
        },
            {
            path: '/user',
            name: "用户管理",
            redirect: "/user/user/list",//重定向路径,用于指向进入页面时显示哪个页面
            meta: "用户",
            component: mainPage,
            children: [{  //包含子组件
                path: 'user/list',
                name: "用户管理",
                component: UserList
            }, {
                path: 'user/add',
                name: "用户新增",
                component: UserAdd
            },
                {
                    path: 'user/detail/:userId',
                    name: "家庭详情",
                    component: UserDetail
                },
                {
                    path: 'user/detailAdd/:userId',//带参数
                    name: "家庭详情新增",
                    component: UserDetailAdd
                },
                {
                    path: 'user/edit/:userId',
                    name: "用户修改",
                    component: UserEdit
                },

            ]
        },
 ]
});
router.beforeEach((to, from, next) => {
    var userToken = $cookies.get("userToken");
    //to即将进入的目标路由对象,from当前导航正要离开的路由, next  :  下一步执行的函数钩子
    if (to.path === '/login') {// 如果即将进入登录路由,则直接放行
        next();
        return;
    }
    if (userToken) {//userToken是否失效,失效进入登录页面
        next();
    } else {
        next({
            path: '/login',
            query: {redirect: to.fullPath}
        })
    }

});


export default router

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import app from './modules/app'
import errorLog from './modules/errorLog'
Vue.use(Vuex)
const store = new Vuex.Store({
  modules: {
    app,  //页面缓存功能 获取一些项目全局数据
    tagsView//多标签页实现  操作路由数据
  },
})

export default store


app.js


const app = {
  state: {//state为单一状态树,在state中需要定义我们所需要管理的数组、对象、字符串等等,只有在这里定义了,在vue.js的组件中才能获取你定义的这个对象的状态
    sidebar: {
      //opened: !+Cookies.get('sidebarStatus'),
       opened:true,//默认打开
      withoutAnimation: false
    },
    currModule:{},//当前模块菜单数据
      selectMenu:[],//选中菜单
    routers:[],//
    selectMainModule:false,
  },
  mutations: {//更改store中state状态的唯一方法就是提交mutation
    TOGGLE_SIDEBAR: state => {//点击收缩功能触发
      state.sidebar.opened = !state.sidebar.opened
      state.sidebar.withoutAnimation = false
    },
    CLOSE_SIDEBAR: (state, withoutAnimation) => {//关闭时触发
     // Cookies.set('sidebarStatus', 1)
      state.sidebar.opened = false
      state.sidebar.withoutAnimation = withoutAnimation
    },
      SET_ROUTERS(state,routers){//设置路由
      state.routers=routers;
      },
      CURR_MODUE:(state,module)=>{
          state.currModule=module;//当前模块菜单数据
      },
      CURR_MENU(state,menu){
          state.currMenu=menu;
      },
      SELECT_MENU(state,selectMenu){
          state.selectMenu=selectMenu;//选中菜单
      },
      SELECT_MAIN_MODULE(state){
          state.selectMainModule=!state.selectMainModule;
      },

  },
  actions: {//action可以提交mutation
    toggleSideBar({ commit }) {
      commit('TOGGLE_SIDEBAR')
    },
    closeSideBar({ commit }, { withoutAnimation }) {
      commit('CLOSE_SIDEBAR', withoutAnimation)
    },
      setRouters({ commit },routers){
          commit('SET_ROUTERS', routers)
      },
      setCurrModule({ commit },module){
          commit('CURR_MODUE', module)
      },
      setSelectMenu({ commit },selectMenu){
          commit('SELECT_MENU', selectMenu)
      },
      selectMainModule({ commit }){
          commit('SELECT_MAIN_MODULE')
      },

  }
}

export default app

tagsView.js
const tagsView = {
  state: {
    visitedViews: []  ,//存放所有浏览过但不重复的路由数据
    
  },
  mutations: {
    ADD_VISITED_VIEWS: (state, view) => {//打开新页签,添加路由数据方法
       //some() 用于检测数组中的元素是否满足指定条件
        if (state.visitedViews.some(v => v.path === view.path)) return
            state.visitedViews.push(Object.assign({}, view, {
              title: view.name || 'no-name'
            }))

    },
    DEL_VISITED_VIEWS: (state, view) => {//关闭选中页面,删除路由
      for (const [i, v] of state.visitedViews.entries()) {
        
        if (v.path === view.path) {
          state.visitedViews.splice(i, 1)
          break
        }
      }
      
    },
    DEL_OTHERS_VIEWS: (state, view) => {//关闭其他页面,删除路由
      for (const [i, v] of state.visitedViews.entries()) {
        if (v.path === view.path) {
          state.visitedViews = state.visitedViews.slice(i, i + 1)
          break
        }
      }
      
    },
    DEL_ALL_VIEWS: (state) => {
      state.visitedViews = []
     
    },
    UPDATE_VISITED_VIEW: (state, view) => {
      for (let v of state.visitedViews) {
        if (v.path === view.path) {
          v = Object.assign(v, view)
          break
        }
      }
    }
  },
  actions: {
    addVisitedViews({ commit }, view) {
      commit('ADD_VISITED_VIEWS', view)
    },
    delVisitedViews({ commit, state }, view) {//删除数组中路由,需要再次刷新路由,这是一个异步过程,需要回调函数Promise()

      return new Promise((resolve) => {//resolve 成功后回调的方法
        commit('DEL_VISITED_VIEWS', view)
        resolve([...state.visitedViews])

      })
    },
    delOthersViews({ commit, state }, view) {
      return new Promise((resolve) => {
        commit('DEL_OTHERS_VIEWS', view)
        resolve([...state.visitedViews])
      })
    },
    delAllViews({ commit, state }) {
      return new Promise((resolve) => {
        commit('DEL_ALL_VIEWS')
        resolve([...state.visitedViews])
      })
    },

    updateVisitedView({ commit }, view) {
      commit('UPDATE_VISITED_VIEW', view)
    }
  }
}

export default tagsView

路由跳转方法
法1

 this.$router.replace('/');
 或者
   this.$router.push({
        name: `TestVueRouterTo`,
        params: {
          page: '1', code: '8989'
        }
      })

介绍:跳转到指定页面,常与登录连用,在使用时直接调用store的方法,把值存储进去,这样跳转页面就会有各种信息,避免必须手动刷新一下才会显示信息。
调用store.js中方法

this.$store.dispatch('setRouters',JSON.parse(localStorage.getItem("menu")))

法2
不带参数跳转页面

<router-link :to="'/server/menuConfig/menuAdd'">
                    <el-button type="primary">新增菜单</el-button>
                </router-link>

带参数跳转

  <router-link :to="{name:'菜单编辑',params:scope.row}">
                            <el-button type="text" size="small">编辑</el-button>
                        </router-link>

注:params传参 参数不会在路径上显示,但是刷新之后参数会消失
query传参 参数会在路径上显示,刷新之后参数不会会消失
js中
获取路由中参数
this. r o u t e . p a r a m s . p a g e / / q u e r y 传 参 t h i s . route.params.page //query传参 this. route.params.page//query传参this.router.params.page //params传参

上一篇:Git stash深解


下一篇:892-git各阶段版本回退命令