国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Vue全家桶(四):Vue Router 路由

這篇具有很好參考價值的文章主要介紹了Vue全家桶(四):Vue Router 路由。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

Vue Router

1. 相關理解

1.1 Vue Router的理解

Vue的一個插件庫,專門用來實現(xiàn)SPA應用

1.2 對SPA應用的理解

  1. 單頁 Web 應用 (single page web application,SPA
  2. 整個應用只有一個完整的頁面
  3. 點擊頁面中的導航鏈接不會刷新頁面,只會做頁面的局部更新
  4. 數(shù)據(jù)需要通過 ajax 請求獲取

Vue全家桶(四):Vue Router 路由

1.3 路由的理解

  1. 什么是路由?
  • 一個路由就是一組映射關系(key - value),多個路由需要路由器(router)進行管理
  • key為路徑,value可能是function或component

在開發(fā)中,路由分為后端路由和前端路由
2. 路由分類
1)后端路由
i. 概念:根據(jù)不同的用戶URL 請求,返回不同的內(nèi)容,value是function,用于處理客戶端提交的請求
ii.本質(zhì):服務器接收到一個請求時,根據(jù)請求路徑找到匹配的函數(shù)來處理請求,返回響應數(shù)據(jù)

后端路由根據(jù)不同的URL地址分發(fā)不同的資源
Vue全家桶(四):Vue Router 路由

2)前端路由
i. 概念:根據(jù)不同的用戶事件,顯示不同的頁面內(nèi)容,value是component,用于展示頁面內(nèi)容
ii. 本質(zhì):當瀏覽器的路徑改變時,對應的組件就會顯示
前端路由負責事件監(jiān)聽,觸發(fā)事件后通過事件函數(shù)渲染不同內(nèi)容
Vue全家桶(四):Vue Router 路由

2. 基本路由

2.1 vue-router使用步驟

  1. 安裝vue-router命令:npm i vue-router@3
    vue2版本使用vue-router的3版本
    vue3版本使用vue-router的4版本
  2. 應用插件:Vue.use(VueRouter)
  3. 編寫router配置項 router/index.js

文件目錄結構
Vue全家桶(四):Vue Router 路由

Vue2的vue-router

import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

//創(chuàng)建router實例對象,去管理一組的路由規(guī)則
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//暴露router
export default router

Vue3的vue-router

import { createRouter, createWebHistory } from 'vue-router'
//引入組件
import Home from '../views/Home.vue'
import About from '../views/About.vue'
//等價于
//const Home = () => import('../views/Home.vue')
//const About = () => import('../views/About.vue')

//聲明一個路由規(guī)則,訪問home,加載Home組件
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

// 創(chuàng)建一個路由
const router = createRouter({
  //模式為歷史模式,請求過的路由會push,類似于window.history.pushState() 
  history: createWebHistory(process.env.BASE_URL),
  //路由規(guī)則
  routes
})
//缺省暴露路由
export default router

src/main.js
Vue全家桶(四):Vue Router 路由

  1. 路由的三種模式

hash模式:
使用URL的hash值來作為路由,用來指導瀏覽器動作,對服務器端完全無用,支持所有瀏覽器

對于一個url來說,什么是hash值?—— #及其后面的內(nèi)容就是hash值。
hash值不會包含在 HTTP 請求中,即:hash值不會帶給服務器。

  • 地址中永遠帶著#號,不美觀 。
  • 若以后將地址通過第三方手機app分享,若app校驗嚴格,則地址會被標記為不合法。
  • 兼容性較好。

history模式:

  • 地址干凈,美觀 。
  • 兼容性和hash模式相比略差。
  • 應用部署上線時需要后端人員支持,解決刷新頁面服務端404的問題。

Vue全家桶(四):Vue Router 路由

abstract模式:
支持所有JavaScript運行模式,如果發(fā)現(xiàn)沒有瀏覽器的API,路由會自動強制進入這個模式。

  1. 路由兩種自帶標簽
    a. 實現(xiàn)切換
    <router-link></router-link> 瀏覽器會倍替換為a標簽
    active-class 可配置高亮樣式
    b. 展示指定位
    <router-view></router-view>
<router-link active-class="active" to="/">Home</router-link> 

2.2 幾個注意點

  1. 路由組件通常存放在 pages 文件夾,一般組件通常存放在 components 文件夾
    路由組件:是指由路由渲染出來的組件,由<router-view>渲染弄出來的組件
    一般組件:一般要寫組件標簽,如<Banner/>
    比如上一節(jié)的案例就可以修改為
    src/pages/Home .vue
    src/pages/About.vue
    src/router/index.js
    src/components/Banner.vue
    src/App.vue

  2. 通過切換,“隱藏”了的路由組件,默認是被銷毀掉的,需要的時候再去掛載。

  3. 每個組件都有自己的$route屬性,里面存儲著自己的路由信息。

  4. 整個應用只有一個router,可以通過組件的$router屬性獲取到。

路由有兩種全局屬性
$route : 當前正在訪問的路由
$router:代表整個大的路由器的對象

2.3 觸發(fā)路由

App.vue 觸發(fā)路由的幾種操作

<template>
  <div id="nav">
	<!-- router-link與a標簽相比有事件處理程序,會渲染成a標簽,to指定路徑,放到URL中-->
    <router-link to="/">Home</router-link> |
    <router-link to="/about" >關于</router-link> |
    <router-link to="/about" custom v-slot="{ navigate }">
      <button @click="navigate" @keypress.enter="navigate" role="link">關于</button>
    </router-link> |
    <button :class="{active:$route.path='/user'}" @click="$router.push('/user')">個人中心</button>|
    <button @click="$router.go(-1)">返回</button>|
    {{$route.path}}
  </div>
  <hr>
  <router-view/>
</template>

Vue全家桶(四):Vue Router 路由
Vue全家桶(四):Vue Router 路由
若要一個頁面顯示三個不同的組件
App.vue

<template>
  <div id="nav">
<!--     router-link與a標簽相比有事件處理程序,會渲染成a標簽,to指定路徑,放到URL中-->
    <router-link to="/">Home</router-link> |
    <router-link to="/about" >關于</router-link> |
    <router-link to="/about" custom v-slot="{ navigate }">
      <button @click="navigate" @keypress.enter="navigate" role="link">關于</button>
    </router-link> |
    <button :class="{active:$route.path=='/user'}" @click="$router.push('/user')">個人中心</button>|
    <button @click="$router.go(-1)">返回</button>|
    {{$route.path}}
  </div>
  <hr>
  <!-- name對應組件名稱,中間一個缺省為home-->
  <router-view class="one" name="User"></router-view>
  <router-view class="two" ></router-view>
  <router-view class="three" name="About"></router-view>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
#nav {
  padding: 30px;
}
#nav a {
  font-weight: bold;
  color: #2c3e50;
}
#nav a.router-link-exact-active {
  color: #42b983;
}
.active {
  color: red !important
}
.one {
  width: 25%;
  height: 300px;
  float: left;
  background-color: #42b983;
}
.two {
  width: 50%;
  height: 300px;
  float: left;
  background-color: cornflowerblue;
}
.three {
  width: 25%;
  height: 300px;
  float: left;
  background-color: coral;
}
</style>

index.js

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import User from '../views/User.vue'
import About from '../views/About.vue'
const routes = [
  {
    path: '/',
    name: 'Home',
    //對象格式,排序也有關系的
    components: {
      default: Home,
      About,
      User
    }
    // component: Home
  },
  {
    path: '/user',
    name: 'user',
    component: User
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

Vue全家桶(四):Vue Router 路由
Vue全家桶(四):Vue Router 路由

2.4 嵌套路由

  1. 配值路由規(guī)則,使用children配置項
    router/index.js路由設置
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import User from '../views/User.vue'
import About from '../views/About.vue'
import Order from '../views/UserOrder.vue'
import Setting from '../views/UserSetting.vue'

//等價于
//const Home = () => import('../views/Home.vue')
//const About = () => import('../views/About.vue')
import * as path from "path";
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/user',
    name: 'user',
    component: User,
    //子路由,/user/order
    children: [
        //設置默認組件
      {
        path: '',
        component: Order
      },
      {
        path: 'order',    //此處不要帶斜杠
        component: Order
      },
      {
        path: 'setting',
        component: Setting
      }
    ]
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

  1. 跳轉
    <router-link to="/user/order">我的訂單</router-link>

User.vue

<template>
  <div class="about">
    <h1>This is an User page</h1>
    <br>
    <div class="menu">
      <ul>
        <!-- 跳轉要寫完整路徑 -->
        <li><router-link to="/user/order">我的訂單</router-link></li>
        <li><router-link to="/user/setting">個人設置</router-link></li>
      </ul>

    </div>
    <div class="content">
      <router-view></router-view>
    </div>

  </div>
</template>
<script>
export default {
  name: "User"
}
</script>
<style scoped>
.menu {
  width: 30%;
  height: 300px;
  background-color: #42b983;
  float: left;
}
.content {
  width: 70%;
  height: 300px;
  background-color: floralwhite;
  float: right;
}
</style>

Vue全家桶(四):Vue Router 路由

Vue全家桶(四):Vue Router 路由

2.5 路由傳遞參數(shù)方式

Vue全家桶(四):Vue Router 路由
上個嵌套路由的例子,“我的訂單”和“個人設置”是采用切換組件來實現(xiàn),下邊采用傳遞參數(shù)來實現(xiàn)頁面的切換,即同個模板,傳遞參數(shù)值來切換

2.5.1 params 方式
  1. 傳遞參數(shù)

User.vue

<template>
  <div >
    <h1>This is an User page</h1>
    <br>
    <div class="menu">
        ……
      <ul>
        <li v-for="item in article">
         <!-- 采用:to的形式,否則雙引號的內(nèi)容不生效,無法成/user/page/10的格式-->
         
		 <!-- to的字符串寫法一-->
          <router-link :class="{active:$route.params.pid==item.id}" :to="'/user/page/'+item.id">{{item.title}}</router-link>
          
          <!-- to的字符串寫法 -多參數(shù)寫法二 -->
          <router-link :class="{active:$route.params.pid==item.id}" :to="`/user/page/${item.id}/${item.title}`">{{item.title}}</router-link>
          
		 <!-- to的對象寫法-->
          <router-link :class="{active:$route.params.pid==item.id}" 
          				:to="{
          					name:'newPage',
          					params: {pid:item.id}">{{item.title}}</router-link>
        </li>
      </ul>
    </div>
    <div class="content">
      <router-view></router-view>
    </div>
  </div>
</template>
<script>
export default {
  name: "User",
  data(){
    return {
      article: [
        {id:10, title: '這是文章一'},
        {id:11, title: '這是文章二'},
        {id:12, title: '這是文章三'},
        {id:13, title: '這是文章四'},
        {id:14, title: '這是文章五'},
      ]
    }
  }
}
</script>
<style scoped>...</style>

特別注意:路由攜帶params參數(shù)時,若使用to的對象寫法,則不能使用path配置項,必須使用name配置!

添加一個UserPage.vue

<template>
  <h2>這是文章的模板</h2>
  <!--  $route當前路由,獲取參數(shù)-->
  文章ID:{{$route.params.pid}}
  <br>
  <h1>{{pageid}}</h1>
</template>

<script>
export default {
  name: "UserPage",
  computed: {
    pageid() {
    //獲取當前路由屬性的參數(shù)值pid
      return this.$route.params.pid;
    }

  }
}
</script>
<style scoped></style>

router/index.js路由配置

const routes = [
  ……
  {
    path: '/user',
    name: 'user',
    component: User,
    //子路由,/user/order
    children: [
        //設置默認組件
     ……
      {
       //動態(tài)路由配置
       	name: 'newPage',            //to的對象寫法,要有name配置
        path: 'page/:pid',          //如果由多個參數(shù)則為 path: 'page/:pid/:title/:xxx' 這樣的寫法
        component: Page
      }
    ]
  },
  ……
]

Vue全家桶(四):Vue Router 路由

2.5.2 Query的方式

User.vue

<template>
  <div>
    <h1>This is an User page</h1>
    <br>
    <div class="menu">
     ……
      <ul>
        ……
        <br>
		<!-- 三種格式-->
		<!-- to的字符串寫法一 -->
        <li><router-link to="/user/article?name=zs&age=10">文章一</router-link></li>
        <!-- to的字符串寫法二 -->
        <li><router-link :to="`/user/article?name=${item.name}&age=${item.age}`">文章一</router-link></li>
        
		<!-- to的對象寫法(推薦) -->
        <li>
        	<router-link :to="{
        					path:'/user/article', 
        					query:{
        						name:'lisi', 
        						age:20
        					}}">文章二</router-link>
        </li>
        <br>
        <li><button @click="$router.push({path:'/user/article', query: {name:'word', age:99}})">文章三</button></li>
      </ul>
    </div>
    <div class="content">
      <router-view></router-view>
    </div>

  </div>
</template>
<script>
export default {
  name: "User",
  data(){
    return {
      article: [
        ……
      ]
    }
  }
}
</script>
<style scoped>……</style>

添加一個Article.vue

<template>
  這是文章內(nèi)容
  <br>
  name:{{$route.query.name}}<br>
  age:{{$route.query.age}}<br>
</template>

<script>
export default {
  name: "Article"
}
</script>
<style scoped></style>

router/index.js路由配置

const routes = [
  ……
  {
    path: '/user',
    name: 'user',
    component: User,
    //子路由,/user/order
    children: [
        //設置默認組件
     ……
      {
        path: 'article',     //正常配置
        component: Article
      }
    ]
  },
  ……
]

Vue全家桶(四):Vue Router 路由

2.6 命名路由

作用:可以簡化路由的跳轉
如何使用?

  1. 給路由命名
{
	path:'/demo',
	component:Demo,
	children:[
		{
			path:'test',
			component:Test,
			children:[{
                    name:'hello' //給路由命名
					path:'welcome',
					component:Hello,
				}
			]
		}
	]
}

  1. 簡化跳轉
<!--簡化前,需要寫完整的路徑 -->
<router-link :to="/demo/test/welcome">跳轉</router-link>

<!--簡化后,直接通過名字跳轉 -->
<router-link :to="{name:'hello'}">跳轉</router-link>

<!--簡化寫法配合傳遞參數(shù) -->
<router-link 
	:to="{
		name:'hello',
		query:{
		   id:666,
           title:'你好'
		}
	}"
>跳轉</router-link>

2.7 路由的props配置

props作用:讓路由組件更方便的收到參數(shù),不用一個個的寫$route.query.xxx

{
	name:'xiangqing',
	path:'detail/:id',
	component:Detail,

	//第一種寫法:props值為對象,該對象中所有的key-value的組合最終都會通過props傳給Detail組件
	// props:{a:900}

	//第二種寫法:props值為布爾值,布爾值為true,則把路由收到的所有params參數(shù)通過props傳給Detail組件,不會理會query參數(shù)
	// props:true
	
	//第三種寫法:props值為函數(shù),該函數(shù)返回的對象中每一組key-value都會通過props傳給Detail組件
	props($route) {
		return {
		  id: $route.query.id,
		  title:$route.query.title,
		  a: 1,
		  b: 'hello'
		}
	}
}

跳轉去組件的具體代碼

<template>
  <ul>
      <h1>Detail</h1>
      <li>消息編號:{{id}}</li>
      <li>消息標題:{{title}}</li>
      <li>a:{{a}}</li>
      <li>b:{{b}}</li>
  </ul>
</template>

<script>
export default {
    name: 'Detail',
    //使用props接受路由參數(shù)
    props: ['id', 'title', 'a', 'b'],
    mounted () {
        console.log(this.$route);
    }
}
</script>
<style></style>

2.8 路由跳轉的replace方法

  1. 作用:控制路由跳轉時操作瀏覽器歷史記錄的模式
  2. 瀏覽器的歷史記錄有兩種寫入方式:pushreplace,
  • push是追加歷史記錄
  • replace是替換當前記錄,路由跳轉時候默認為push方法
  1. 開啟replace模式
<router-link :replace="true" ...> News</router-link>
//簡寫
<router-link replace ...> News</router-link>

總結: 瀏覽記錄本質(zhì)是一個棧,默認 push ,點開新頁面就會在棧頂追加一個地址,后退,棧頂指針向下移動,改為 replace 就是不追加,而將棧頂?shù)刂诽鎿Q

2.9 編程式路由導航

  1. 聲明式導航:通過點擊鏈接實現(xiàn)導航的方式 例如:普通網(wǎng)頁中的<a></a> 鏈接或vue 中的<router-link></router-link>
  2. 編程式導航:通過調(diào)用JavaScript形式的API實現(xiàn)導航的方式 例如:普通網(wǎng)頁中的location.href
    編程式路由導航作用:不借助<router-link>實現(xiàn)路由跳轉,讓路由跳轉更加靈活
    具體參數(shù)規(guī)則:
// 字符串(路徑名稱)
this.$router.push('/home')
// 對象
this.$router.push({ path: '/home' })
// 命名的路由(傳遞參數(shù))
this.$router.push({ name: '/user', params: { userId: 123 }})
// 帶查詢參數(shù),變成/register?uname=lisi
this.$router.push({ path: '/register', query: { uname: 'lisi' }})

this.$router.replace({
	name:'xiangqing',
		params:{
			id:xxx,
			title:xxx
		}
})
this.$router.forward() //前進
this.$router.back() //后退
this.$router.go(n) //可前進也可后退,n大于0前進n,小于0后退n

使用

<button @click="$router.go(-1)">返回</button>
<button @click="pushShow(m)">push查看</button>
<script>
...
methods: {
	pushShow(m) {
		this.$router.push({ path: '/register', query: {id: m.id, name: m.title }})
	}
}
...
</script>

2.10 重定向和別名

Vue全家桶(四):Vue Router 路由

2.11 頁面回退

從a頁面=>b頁面=>c頁面,當前在c頁面,執(zhí)行某方法后可以如同按了瀏覽器后退鍵一樣返回b頁面

  1. 若項目使用vue-router ,則使用this.$router.go(-1)
  2. this.$router.back()
  3. window.history.go(-1)

①與②的區(qū)別是:

go(-1): 原頁面表單中的內(nèi)容會丟失:
 1. this.$router.go(-1):后退+刷新;
 2. this.$router.go(0):刷新;
 3. this.$router.go(1):前進;
 
----
 
back(): 原頁表表單中的內(nèi)容會保留;
 
 1. this.$router.back():后退 ;
 2. this.$router.back(0):刷新;
 3. this.$router.back(1):前進;
 

③的區(qū)別是:
history.go(-1)是返回瀏覽器的上一頁,而由于Vue是單頁面應用,有的瀏覽器對于hash變更不認為是兩個不同的頁面,在hash模式下就不會跳回瀏覽器上一頁

2.12 兩個生命周期鉤子 activated、deactivated

activateddeactivated是i路由組件所獨有的兩個鉤子,用于捕獲路由組件的激活狀態(tài)
具體使用:
activatedkeep-alive 緩存的組件激活時調(diào)用。
deactivatedkeep-alive 緩存的組件失活時調(diào)用。
activateddeactivated是配合keep-alive一起使用的,其余不會觸發(fā),

在存在keep-alive的時候可以將activated當作created進行使用
deactivated是組件銷毀的時候觸發(fā),此時的destory是不執(zhí)行的

2.13 keep-alive緩存路由

keep-alive作用:主要用于保留組件狀態(tài)或避免重新渲染。 包裹動態(tài)組件時,會緩存不活動的組件實例,而不是銷毀它們。

Props:

  • include:只有名稱匹配的組件會被緩存。
  • exclude:任何名稱匹配的組件都不會被緩存。
  • max:最多可以緩存多少組件實例。

router-view是vue-router內(nèi)置組件,如果直接包含在keep-alive里面,所有路徑匹配到的組件都會被緩存

場景:用戶在表單輸入的時候,如果切換了頁面再返回,表單輸入的內(nèi)容都被清空了,這是因為組件在切換時,會已處在創(chuàng)建-銷毀的過程中,為節(jié)省時間和資源,采用keep-alive使其保存在緩存中

	created() {
      console.log('About---組件創(chuàng)建');
    },
    unmounted() {
      console.log('About---組件被銷毀');
    },
    activated() {
      console.log('About---keep-alive 緩存的組件激活時調(diào)用');
    },
    deactivated() {
      console.log('About---keep-alive 緩存的組件停用時調(diào)用');
    }

Vue全家桶(四):Vue Router 路由

include設置想要緩存的組件名

//緩存一個路由組件
<keep-alive include="News">     //include中寫想要緩存的組件名,不寫表示全部緩存
    <router-view></router-view>
</keep-alive>

//緩存多個路由組件
<keep-alive :include="['News','Message']"> 
    <router-view></router-view>
</keep-alive>

只要將router-view修改如下代碼,就可實現(xiàn)緩存效果

<router-view v-slot="{ Component }">
    <transition>
      <keep-alive>
        <component :is="Component" />
      </keep-alive>
    </transition>
  </router-view>

這種方法會觸發(fā)actived()deactivated()方法
Vue全家桶(四):Vue Router 路由
可單獨設置exclude使得某些組件不緩存

<router-view v-slot="{ Component }">
    <transition>
      <keep-alive exclude="About">
        <component :is="Component" />
      </keep-alive>
    </transition>
  </router-view>

Vue全家桶(四):Vue Router 路由
為了保證離開一個頁面后再返回仍停留在離開時的狀態(tài),可在組件內(nèi)設置前置守衛(wèi),將離開時的路徑保存下來,待緩存激活active時再設置全局路由

 created() {
    console.log('User---組件創(chuàng)建');
  },
  unmounted() {
    console.log('User---組件被銷毀');
  },
  activated() {
    console.log('User---keep-alive 緩存的組件激活時調(diào)用');
    //回到離開時的狀態(tài)
    this.$router.push(this.path)
  },
  deactivated() {
    console.log('User---keep-alive 緩存的組件停用時調(diào)用');
  },
  beforeRouteLeave(to,from) {
    //獲取離開的路由
    this.path = from.fullPath
    console.log('to----'+to.fullPath);
    console.log('from----'+from.fullPath);
  }

2.14 路由守衛(wèi)

作用:對路由進行權限控制
分類:全局守衛(wèi)、獨享守衛(wèi)、組件內(nèi)守衛(wèi)

  1. 全局守衛(wèi)

前置守衛(wèi):從一個路由跳轉另一個路由之前有一個前置守衛(wèi),前置守衛(wèi)會調(diào)用一個方法,這個方法可以處理跳轉之前的事情。如登錄訪問
Vue全家桶(四):Vue Router 路由

后置守衛(wèi):跳轉過去之后,在內(nèi)容沒顯示之前,有一個后置鉤子
Vue全家桶(四):Vue Router 路由

router/index.js

const routes = [
  {
    path: '/home',
    name: 'Home',
    //重定向到根 兩種方式
    // redirect: '/',
    redirect: {name: 'root'},
    component: Home,
    meta: {
      title: '首頁'
    },
  }]
  
const router = new VueRouter({
	routes 
})

//全局前置守衛(wèi):初始化時執(zhí)行、每次路由切換前執(zhí)行
router.beforeEach((to,from)=>{
  console.log('前置守衛(wèi)');
  //設置即將到達的頁面標題,meta是上方各個路由設置的meta屬性
  document.title = to.meta.title
  console.log('title---'+to.meta.title);
  //打印即將到達的路徑
  console.log('to---'+to.fullPath);
  //false不準跳轉,true則放行
  return true;
})

//全局后置守衛(wèi):初始化時執(zhí)行、每次路由切換后執(zhí)行
router.afterEach((to,form)=>{
  console.log('后置鉤子');
  console.log('to---'+to.fullPath);
  console.log('form---'+form.fullPath);
})

export default router

Vue全家桶(四):Vue Router 路由

const routes = [
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      isAuth: true,
      title: '首頁'
    },
  }]
  
const router = new VueRouter({
	routes 
})

//全局前置守衛(wèi):初始化時執(zhí)行、每次路由切換前執(zhí)行
router.beforeEach((to, from, next) => {
	if(to.meta.isAuth) {         //判斷當前路由是否需要進行權限控制
		if(localStorage.getItem('school') === 'zhejiang'){ //權限控制的具體規(guī)則
			next() //放行
		}else{
			alert('暫無權限查看')
			// next({name:'guanyu'})
		}
	}else{
		next() //放行
	}

//全局后置守衛(wèi):初始化時執(zhí)行、每次路由切換后執(zhí)行	
router.afterEach((to,from)=>{
	if(to.meta.title){ 
		document.title = to.meta.title //修改網(wǎng)頁的title
	}else{
		document.title = 'vue_test'
	}
})
  1. 獨享守衛(wèi)
    獨享守衛(wèi)是在routes 子路由內(nèi)寫守衛(wèi)
beforeEnter(to, from, next){
	if(to.meta.isAuth) {         //判斷當前路由是否需要進行權限控制
		if(localStorage.getItem('school') === 'zhejiang'){ //權限控制的具體規(guī)則
			next() //放行
		}else{
			alert('暫無權限查看')
			// next({name:'guanyu'})
		}
	}else{
		next() //放行
	}
}

Vue全家桶(四):Vue Router 路由

  1. 組件內(nèi)守衛(wèi)
    組件內(nèi)守衛(wèi)是在具體組件內(nèi)寫守衛(wèi)
//進入守衛(wèi):通過路由規(guī)則,進入該組件時被調(diào)用
beforeRouteEnter (to, from, next) {
},
//離開守衛(wèi):通過路由規(guī)則,離開該組件時被調(diào)用
beforeRouteLeave (to, from, next) {
}

Vue全家桶(四):Vue Router 路由文章來源地址http://www.zghlxwxcb.cn/news/detail-489577.html

到了這里,關于Vue全家桶(四):Vue Router 路由的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • Vue入門六(前端路由的概念與原理|Vue-router簡單使用|登錄跳轉案例|scoped樣式|混入(mixin)|插件)

    Vue入門六(前端路由的概念與原理|Vue-router簡單使用|登錄跳轉案例|scoped樣式|混入(mixin)|插件)

    路由(英文:router)就是對應關系 SPA指的是一個web網(wǎng)站只有一個唯一的一個HTML頁面, 所有組件的展示與切換 都在唯一的一個頁面內(nèi)完成。 此時, 不同組件之間的切換 需要通過 前端路由 來實現(xiàn) 總結:在SPA項目中, 不同功能之間的切換 ,要 依賴于前端路由 來完成 通俗移動

    2024年01月22日
    瀏覽(29)
  • vue3 一個基于pinia簡單易懂的系統(tǒng)權限管理實現(xiàn)方案,vue-router動態(tài)路由異步問題解決

    vue3 一個基于pinia簡單易懂的系統(tǒng)權限管理實現(xiàn)方案,vue-router動態(tài)路由異步問題解決

    作為項目經(jīng)驗稀少的vue開發(fā)者來說,在關鍵技術點上的經(jīng)驗不多,我希望通過我的思想和實踐,把好的東西分享在這里,目的是進一步促進技術交流。項目即將完成,權限是最后的收尾工作,好的權限實現(xiàn)方案,可以讓我們沒有后顧之憂,也可以提升項目的運行速度。 在開發(fā)

    2023年04月08日
    瀏覽(96)
  • Vue如何創(chuàng)建一個新頁面以及相關路由配置詳解

    前些天發(fā)現(xiàn)了一個巨牛的人工智能學習網(wǎng)站,通俗易懂,風趣幽默,忍不住分享一下給大家?!緦毑厝肟凇?。 在Vue.js中,路由配置是通過使用Vue Router來完成的。以下是Vue路由配置的基本語法格式: 在上面的代碼中,有幾個重要的屬性和概念: 這些路由配置會被傳遞給 VueR

    2024年01月22日
    瀏覽(18)
  • 路由前置守衛(wèi)router.beforeEach相關用法

    router.beforeEach 是 Vue Router 提供的全局前置守衛(wèi),用于在路由切換之前執(zhí)行一些邏輯。該守衛(wèi)接收三個參數(shù): to : 即將要進入的目標路由對象。 from : 當前導航正要離開的路由。 next : 一個函數(shù),用于 resolve 鉤子。調(diào)用 next 表示路由可以繼續(xù)執(zhí)行。 基本用法如下: 在 beforeEach 鉤

    2024年01月21日
    瀏覽(26)
  • vue全家桶進階之路34:Vue3 路由基本配置

    在Vue3中,路由的基本配置是通過使用Vue Router庫來實現(xiàn)的。以下是Vue3中路由的基本配置步驟: 安裝Vue Router 使用npm或yarn在項目中安裝Vue Router: 創(chuàng)建路由實例 創(chuàng)建一個路由實例并定義路由規(guī)則。路由規(guī)則是一個對象數(shù)組,其中每個對象都定義了一個路由的路徑和組件。 例如

    2023年04月18日
    瀏覽(24)
  • vue Router路由

    vue Router路由

    是 Vue.js 的官方路由。它與 Vue.js 核心深度集成,讓用 Vue.js 構建單頁應用變得輕而易舉。功能包括: 嵌套路由映射 動態(tài)路由選擇 模塊化、基于組件的路由配置 路由參數(shù)、查詢、通配符 展示由 Vue.js 的過渡系統(tǒng)提供的過渡效果 細致的導航控制 自動激活 CSS 類的鏈接 HTML5 his

    2024年02月07日
    瀏覽(17)
  • 路由vue-router

    路由vue-router

    路由(英文:router)就是 對應關系 SPA 指的是一個 web 網(wǎng)站只有 唯一的一個 HTML 頁面 ,所有組件的展示與切換都在這唯一的一個頁面內(nèi)完成。 此時,不同組件之間的切換需要通過前端路由來實現(xiàn)。 結論: 在 SPA 項目中,不同功能之間的切換 ,要依賴于 前端路由 來完成!

    2024年02月07日
    瀏覽(24)
  • vue路由及參數(shù)router

    vue路由及參數(shù)router

    1.1 如果還沒安裝node.js, 則先安裝node.js ,安裝完成后,查看node版本 1.2 安裝淘寶鏡像, 安裝完成后查看npm版本:npm -v 1.3 安裝webpack 1.4 安裝vue全局腳手架,vue-cli2.x使用 npm install -g vue-cli , vue-cli3.x使用 npm install -g @vue/cli 安裝, 查看vue版本: vue -V 1.5 準備工作做好了,開始正

    2024年01月23日
    瀏覽(19)
  • vue3使用vue-router嵌套路由(多級路由)

    vue3使用vue-router嵌套路由(多級路由)

    Vue3 嵌套路由的使用和 Vue2 相差不大,主要的區(qū)別是 Vue3 的路由實例化使用了 createApp() 方法,所以實例化路由時需要傳入根組件。另外,Vue3 的路由對象除了包含 Vue2 中的導航守衛(wèi)、導航鉤子和解析守衛(wèi)等功能外,還新增了 meta prop 和 route prop。 在使用嵌套路由時,建議將路由

    2024年02月03日
    瀏覽(29)
  • 5 分鐘理解 vue-router 原理

    vue-router 原理 路由原理,是面試非常頻繁常問的一個問題 面試官:你了解vue路由原理嗎 ? 回答 :是利用瀏覽器的 history api、 面試官:具體是怎么實現(xiàn)的呢? 回 答 :壞了。。。。。。 針對路由的兩種模式( hash 模式、 history 模式)原理是不一樣的 Hash 模式 hash 模式是比較

    2024年02月16日
    瀏覽(19)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包