最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue路由應(yīng)用詳細(xì)講解

 更新時(shí)間:2022年11月22日 16:22:24   作者:一桿老狙  
路由的本質(zhì)就是一種對應(yīng)關(guān)系,根據(jù)不同的URL請求,返回對應(yīng)不同的資源。那么url地址和真實(shí)的資源之間就有一種對應(yīng)的關(guān)系,就是路由

介紹

vue-router相當(dāng)于vue內(nèi)部跳轉(zhuǎn)鏈接,將需要切換的頁面在vue-router里注冊,在項(xiàng)目里配置就能完成頁面的切換,它不僅能完成項(xiàng)目的切換,還能實(shí)現(xiàn)參數(shù)的傳遞,它還有個(gè)很重要的功能路由導(dǎo)航守衛(wèi)(導(dǎo)航守衛(wèi)分為前置導(dǎo)航守衛(wèi),后置導(dǎo)航守衛(wèi),組件內(nèi)置導(dǎo)航守衛(wèi),常用就是前置導(dǎo)航守衛(wèi),設(shè)置用戶登錄可訪問的界面和未登錄可訪問的界面,也相當(dāng)于二次攔截,(axios請求攔截器是第一次攔截))。

路由跳轉(zhuǎn)和傳參

重點(diǎn):

在vue-router中,有兩大對象被掛載到了實(shí)例this;

$route(只讀、具備信息的對象);

$router(具備功能的函數(shù));

1.router-link(類似a標(biāo)簽)

路由配置:

// 路由配置
 {
   path: '/pkproperties', // 路徑
   name:'pkproperties', // 路由名,path路徑必寫,用name跳轉(zhuǎn)的時(shí)候是根據(jù)name名找到path進(jìn)行跳轉(zhuǎn)
   component: () => import('@/views/pkproperties'), // 組件(組件文件名為index的可省略),路由懶加載寫法
   redirect: '', // 路由重定向,就是當(dāng)一個(gè)頁面需要切換多個(gè)路由的時(shí)候,這里面填的是首次進(jìn)入頁面展示的路由組件地址
   hidden: true,
   children: [] // 嵌套路由,當(dāng)一頁有很多路由需要切換的時(shí)候,就需要用到嵌套路由
  },
// 組件內(nèi)使用
   <router-link to="/pkproperties">點(diǎn)擊跳轉(zhuǎn)</router-link>  // path路徑跳轉(zhuǎn)
   <router-link to="{name:'pkproperties',query:{id:1}}">點(diǎn)擊跳轉(zhuǎn)</router-link>  // 使用命名路由name跳轉(zhuǎn)

傳參配置:

 {
   path: '/pkproperties', // 路徑
   name:'pkproperties', // 路由名,path路徑必寫,用name跳轉(zhuǎn)的時(shí)候是根據(jù)name名找到path進(jìn)行跳轉(zhuǎn)
   component: () => import('@/views/pkproperties'), // 組件(組件文件名為index的可省略)
   hidden: true
  },
   // 使用命名路由傳參,可以傳遞基本數(shù)據(jù)類型和數(shù)組和對象
   <router-link to="{name:'pkproperties',query:{id:1}}">點(diǎn)擊跳轉(zhuǎn)</router-link>  // name名跳轉(zhuǎn),query傳遞參數(shù)
   <router-link to="{name:'pkproperties',params:{id:1}}">點(diǎn)擊跳轉(zhuǎn)</router-link>  // name名跳轉(zhuǎn),params傳遞參數(shù)
   this.$route.query.id // 獲取傳遞的參數(shù)(.傳遞參數(shù)的鍵名)
   this.$route.params.id // 獲取傳遞的參數(shù)(.傳遞參數(shù)的鍵名)

2.編程式路由跳轉(zhuǎn)(最常用的,不受時(shí)機(jī)、條件的限制)

路由配置:

{
   path: '/pkproperties', // 路徑
   name:'pkproperties', // 路由名,path路徑必寫,用name跳轉(zhuǎn)的時(shí)候是根據(jù)name名找到path進(jìn)行跳轉(zhuǎn)
   component: () => import('@/views/pkproperties'), // 組件(組件文件名為index的可省略)
   hidden: true
  },

傳參配置:

methods:{
   onSkipTransferParameters(){
   // params傳參
        this.$router.push({
           name: "pkproperties",
           params: { 
           name: '小明',
           id: 1,
          },
        });
     onSkipTransferParameters(){
   // query傳參
        this.$router.push({
           name: "pkproperties",
           query: { 
           name: '小明',
           id: 1,
          },
        });
   }
 // 獲取傳遞的參數(shù)
 this.$route.params.name // 獲取就是在當(dāng)前跳轉(zhuǎn)的組件內(nèi)調(diào)用$route實(shí)例,是用params就.params.鍵名獲取值
 this.$route.query.name // 獲取就是在當(dāng)前跳轉(zhuǎn)的組件內(nèi)調(diào)用$route實(shí)例,是用query就.query.鍵名獲取值

query傳參在刷新界面后傳遞的數(shù)據(jù)不會丟失,params傳遞的參數(shù)刷新界面后會丟失參數(shù)。

3.路由重定向redirect需要用到傳參的業(yè)務(wù)

   { path:"/", redirect: {path:"pkproperties", query:{Pid:'1'}} },
   { path:"pkproperties", component: ()=>import("../views/pkproperties") }

解決路由重復(fù)點(diǎn)擊路由沉積的問題

// 把這段代碼直接粘貼到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
  VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => { })
};

注意:一定要寫在 Vue.use(VueRouter)之前否則無效

解決路由跳轉(zhuǎn)后不能回到頂部的頁面頂部的問題

在跳轉(zhuǎn)到的組件里配置下面的代碼即可

 mounted() {
    /**
     * 路由跳轉(zhuǎn)回到頂部
     */
    // chrome
    document.body.scrollTop = 0;
    // firefox
    document.documentElement.scrollTop = 0;
    // safari
    window.pageYOffset = 0;
  },

路由導(dǎo)航守衛(wèi)和案例展示

路由前置導(dǎo)航守衛(wèi)(beforeEach

    // 全局導(dǎo)航守衛(wèi)beforeEach
router.beforeEach((to, from, next) => {
	// to要到哪個(gè)路由去
    // from從哪個(gè)路由來
    // next下一步(無論失敗與否都要調(diào)用,否則會阻止程序繼續(xù)執(zhí)行)
}

案例1中使用(攔截未登錄用戶和白名單設(shè)置):

permission.js文件下配置(permission文件最好和main文件在同一目錄下創(chuàng)建)

import router from './router'
import { getToken } from '@/common/TokenStore'
const whiteList = ['/login', '/register'] // 白名單登錄注冊界面無需驗(yàn)證Token是否登錄直接放行
// 全局導(dǎo)航守衛(wèi)beforeEach
router.beforeEach((to, from, next) => {
	// 白名單中路由直接放行
	if (whiteList.indexOf(to.path) !== -1) {
		next()
		return
	}
	// 判斷需要登錄身份認(rèn)證的路由
	const token = getToken() // 獲取token
	if (token) {
		next()
	} else {
		next(`/login`) // 如果登錄不存在,重定向到登錄界面
	}
})

main.js文件下引入即可

import './permission' // 引入即可

案例2中使用(設(shè)置Tokne失效實(shí)現(xiàn)攔截,Tokne失效就導(dǎo)航會登錄界面重新登錄,未失效就不執(zhí)行操作)

login.vue(登錄組件登錄成功后保存Token和保存獲取Token的當(dāng)前時(shí)間戳在本地)

    methods: {
      // 登錄
      handleLogin() {
        this.$axios.post('/api/Login',{
         username: this.loginForm.username, // 用戶名
         password: this.loginForm.password // 密碼
        }).then(res => { 
          if(res.data.code != 0) return this.$message.error(res.data.message) // code 不等于0,返回失敗的結(jié)果,(這的判斷參數(shù)是根據(jù)后端返回的數(shù)據(jù)進(jìn)行的,不是固定的)
          if(res.data.code == 0){
            this.$message.success('登錄成功')
            // 存儲token開始時(shí)間
            window.localStorage.setItem('tokenStartTime',new Date().getTime())
            // 存儲token
            window.localStorage.setItem('token',res.data.data.token)
            this.$router.push('/home/ks')
          }else {
            this.$message.error('登錄失敗')
          }
        })
      }
}

permission.js(將保存的Token獲取時(shí)間和當(dāng)前時(shí)間進(jìn)行一個(gè)差值的比較,如果小于我們設(shè)定的Token失效時(shí)間,就證明登錄沒有過期可繼續(xù)訪問,如果大于就登錄過期Token失效需要重新登錄獲取。)

// 導(dǎo)入element提示語的組件可以去element-ui查看用法,這是按需引入的
import {
    Message
} from 'element-ui'
// 添加請求攔截器
// 攔截器的第二部分,第一部分在main.js里面
router.beforeEach((to, from, next) => {
  // 獲取存儲localStorage的token
  let token = window.localStorage.getItem('token')
  // 獲取存儲token的開始時(shí)間
  const tokenStartTime = window.localStorage.getItem('tokenStartTime')
  // 后臺給出的token有效時(shí)間為一天,這個(gè)是后端給的時(shí)間以后端為準(zhǔn)
  const timeOver = 86400000
  // 獲取當(dāng)前時(shí)間
  let date = new Date().getTime()
  // 當(dāng)前時(shí)間減去獲取Token的時(shí)間如果大于說明是token過期了
  if(date - tokenStartTime > timeOver) {
      token = null // Token過期賦值為null
  }
  // 如果token過期了
  if (!token) {
    if (to.path == '/login') return next()
    // 注意要import element的Message組件
    Message.error("登錄狀態(tài)過期,請重新登錄")
    return next('/login')
    // 如果token沒有過期,又是選擇了登錄頁面就直接重定向到首頁,不需要重新輸入賬戶密碼
  } else if (to.path == '/login') {
    return next('/home/ks')
  }
  next()
 
})
export default router

全局后置守衛(wèi)(afterEach

router.afterEach((to,from)=>{<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->})

組件內(nèi)守衛(wèi)(相當(dāng)于給組件增加生命周期)

beforeRouteEnter 進(jìn)入組件之前
beforeRouterEnter(to,from,next){}

beforeRouteUpdate 組件被復(fù)用時(shí)調(diào)用
beforeRouterUpdate(to,from,next){}

beforeRouteLeave 離開組件時(shí)調(diào)用
beforeRouteLeave(to,from,next){}

訪問外部鏈接

vue內(nèi)部跳轉(zhuǎn)可以通過vue-router中的this.$router.push()和rout-link 來實(shí)現(xiàn),這里在說一下想要訪問外部鏈接的方法

1.window.location.href = url(不新開一個(gè)頁面,直接在當(dāng)前頁面跳轉(zhuǎn))

methods:{
  onSkip(){
    window.location.
  }
}

2.window.open(“url”, “_blank”)(打開一個(gè)新頁面跳轉(zhuǎn))

methods:{
  onSkip(){
    window.open("https://xxx.xxx.xxx/", "_blank");
  }
}

3.手動創(chuàng)建a標(biāo)簽,然后默認(rèn)點(diǎn)擊

 var a = document.createElement("a");
     a.setAttribute("href", "www.baidu.com");
     a.setAttribute("target", "_blank");
     a.click();

到此這篇關(guān)于Vue路由應(yīng)用詳細(xì)講解的文章就介紹到這了,更多相關(guān)Vue路由內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

札达县| 奉化市| 定边县| 吴川市| 锦屏县| 兴海县| 菏泽市| 华亭县| 富民县| 兴宁市| 尚志市| 区。| 麻栗坡县| 肇庆市| 兴山县| 额敏县| 宁陕县| 江源县| 荥阳市| 齐河县| 柘城县| 布尔津县| 定西市| 长兴县| 乡城县| 湖北省| 彰化县| 陆丰市| 文昌市| 贵定县| 昌邑市| 噶尔县| 宁远县| 德清县| 治县。| 崇信县| 忻城县| 慈利县| 霞浦县| 常山县| 福鼎市|