Vue3 - 路由

四、Vue中的ajax

4.1 vue脚手架配置代理

解决开发环境Ajax跨域问题

Vue CLI文档

方法一

​ 在vue.config.js中添加如下配置:

devServer:{
  proxy:"http://localhost:5000"
  //配置代理服务器,这个路径端口号要与传送数据的服务器端口号一致
}
复制代码

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理。不能灵活的控制请求是否走代理,这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:5000
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 ,自身带有同名资源,则优先使用自身资源(优先匹配前端资源)。

方法二

​ 编写vue.config.js配置具体代理规则:

module.exports = {
	devServer: {
      proxy: {
      '/api1': {// 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',// 代理目标的基础路径,路径到5000就不往后写了
        changeOrigin: true,
        pathRewrite: {'^/api1': ''} //重写路径
      },
      '/api2': {// 匹配所有以 '/api2'开头的请求路径
        target: 'http://localhost:5001',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api2': ''} //重写路径
      }
    }
  }
}
/*
   changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
   changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
   changeOrigin默认值为true
*/

说明:

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。

vue.config.js

module.exports = {
    pages: {
        index: {
            // page 的入口
            entry: 'src/main.js',

        },
    },
    lintOnSave: false, //关闭语法检查
    //开启代理服务器(方式一)
    // devServer: {
    //     proxy: 'http://localhost:5000'
    // },
    //开启代理服务器(方式二)
    devServer: {
        proxy: {
            // /atguigu ,/demo 叫前缀
            '/atguigu': {
                target: 'http://localhost:5000',
                // 路径到5000就不往后写了
                pathRewrite: { '^/atguigu': '' },
                // 取消发送请求的前缀名
                // ws: true, //用于支持websocket,不写默认为true
                // changeOrigin: true //用于控制请求头中的host值,不写默认为true
            },
            '/demo': {
                target: 'http://localhost:5001',
                pathRewrite: { '^/demo': '' },
                // ws: true, //用于支持websocket
                // changeOrigin: true //用于控制请求头中的host值
            }
        }
    }
}
复制代码

App.vue

<template>
  <div>
    <button @click="getStudents">获取学生信息</button>
    <button @click="getCars">获取汽车信息</button>
  </div>
</template>

<script>
import axios from "axios";
// 引入axios,需要先下载,npm i axios

export default {
  name: "App",
  methods: {
    //   方式一:axios url就是请求地址http://localhost:8080/students
   getStudents() {
      axios.get("http://localhost:8080/students").then(
        // 将端口号改为默认的端口号
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
  // 方式二:axios url请求在端口号之后加上前缀名
    getStudents() {
      axios.get("http://localhost:8080/atguigu/students").then(
        // 将端口号改为默认的端口号
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
    // 方式二:axios url请求在端口号之后加上前缀名
    getCars() {
      axios.get("http://localhost:8080/demo/cars").then(
        (response) => {
          console.log("请求成功了", response.data);
        },
        (error) => {
          console.log("请求失败了", error.message);
        }
      );
    },
  },
};
</script>

4.2 AJAX案例实操

Github搜索案例

image.png

4.3 vue-resource(发送AJAX的插件库)

1.先安装插件库
npm i vue-resource
2.在main.js中引入插件库
//引入插件
import vueResource from 'vue-resource'
3.在main.js中使用插件
//使用插件
Vue.use(vueResource)
4.使用方法与axios一致,只是吧axios.get()替换成this.$http.get()

4.4 插槽

父组件向子组件传递带数据的标签,当一个组件有不确定的结构时,就需要使用slot技术,注意:插槽内容是在父组件中编译后,再传递给子组件的。

  1. 作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件

  2. 分类:默认插槽、具名插槽、作用域插槽

  3. 使用方式:

    1. 默认插槽:

      父组件中:
              <Category>
                 <div>html结构1</div>
              </Category>
      子组件中:
              <template>
                  <div>
                     <!-- 定义插槽 -->
                     <slot>插槽默认内容...</slot>
                  </div>
              </template>
      复制代码
      
    2. 具名插槽:

      父组件中:
              <Category>
                  <div slot="center">
      <!-- 放入指定名字的插槽中-->
                    <div>html结构1</div>
                  </div>
      <!-- 两种写法,但 v-slot:footer只能用在template标签中-->
                  <template v-slot:footer>
                     <div>html结构2</div>
                  </template>
              </Category>
      子组件中:
              <template>
                  <div>
                     <!-- 定义插槽 -->
                     <slot name="center">插槽默认内容...</slot>
                     <slot name="footer">插槽默认内容...</slot>
                  </div>
              </template>
      复制代码
      
    3. 作用域插槽:

      1. 理解:数据在组件的自身(在slot插槽定义的那个组件里面),但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

      2. 具体编码:

            父组件中:
                   <Category>
                   //必须包裹template标签,scope属性标签必带,收到数据,但" "内名字随意起
                           <template scope="scopeData">
                                   <!-- 生成的是ul列表 -->
                                   <ul>
                                        <li v-for="g in scopeData.games" :key="g">{{g}}</li>
                                   </ul>
                           </template>
                   </Category>
        
                   <Category>
                           <template slot-scope="scopeData">
                                   <!-- 生成的是h4标题 -->
                                <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
                           </template>
                   </Category>
            子组件中:
            <template>
                <div>
                    <slot :games="games"></slot>
                    //通过插槽将数据从子组件传递给父组件
                </div>
            </template>
        
            <script>
                export default {
                    name:'Category',
                    props:['title'],
                    //数据在子组件自身
                    data() {
                        return {
                            games:['红色警戒','穿越火线','劲舞团','超级玛丽']
                        }
                    },
                }
            </script>
        复制代码
        

      备注:作用域插槽也可以取名字

4.4.1 不使用插槽

image.png Category

<template>
  <div class="category">
    <h3>{{ title }}分类</h3>
    <ul>
      <li v-for="(item, index) in listData" :key="index">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Category",
  props: ["title", "listData"],
};
</script>

<style scoped>
.category {
  background-color: skyblue;
  width: 200px;
  height: 300px;
}
h3 {
  text-align: center;
  background-color: orange;
}
video {
  width: 100%;
}
img {
  width: 100%;
}
</style>

App.vue

<template>
  <div class="container">
    <Category title="美食" :listData="foods"></Category>
    <Category title="游戏" :listData="games"></Category>
    <Category title="电影" :listData="films"></Category>
  </div>
</template>

<script>
import Category from "./components/Category";
export default {
  name: "App",
  components: { Category },
  data() {
    return {
      foods: ["火锅", "烧烤", "小龙虾", "牛排"],
      games: ["红色警戒", "穿越火线", "劲舞团", "超级玛丽"],
      films: ["《教父》", "《拆弹专家》", "《你好,李焕英》", "《与神同行》"],
    };
  },
};
</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-around;
}
</style>
复制代码

4.4.2 默认插槽

image.png App.vue

<template>
	<div class="container">
		<Category title="美食" >
			<img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
		</Category>

		<Category title="游戏" >
			<ul>
			     <li v-for="(g,index) in games" :key="index">{{g}}</li>
			</ul>
		</Category>

		<Category title="电影">
			<video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
		</Category>
	</div>
</template>

<script>
	import Category from './components/Category'
	export default {
		name:'App',
		components:{Category},
		data() {
			return {
                            foods:['火锅','烧烤','小龙虾','牛排'],
                            games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
                            films:['《教父》','《拆弹专家》','《你好,李焕英》','《与神同行》']
			}
		},
	}
</script>

<style scoped>
	.container{
		display: flex;
		justify-content: space-around;
	}
</style>

复制代码

Category

<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
		<slot>我是一些默认值,当使用者没有传递具体结构时,我会出现</slot>
	</div>
</template>

<script>
	export default {
		name:'Category',
		props:['title']
	}
</script>

<style scoped>
	.category{
		background-color: skyblue;
		width: 200px;
		height: 300px;
	}
	h3{
		text-align: center;
		background-color: orange;
	}
	video{
		width: 100%;
	}
	img{
		width: 100%;
	}
</style>
复制代码

4.4.3 具名插槽

image.png Category

<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
		<slot name="center">定义一个名为center的插槽</slot>
		<slot name="footer">定义一个名为footer的插槽</slot>
	</div>
</template>

<script>
	export default {
		name:'Category',
		props:['title']
	}
</script>

<style scoped>
	.category{
		background-color: skyblue;
		width: 200px;
		height: 300px;
	}
	h3{
		text-align: center;
		background-color: orange;
	}
	video{
		width: 100%;
	}
	img{
		width: 100%;
	}
</style>
复制代码

App.vue

<template>
  <div class="container">
    <Category title="美食">
    //放入center插槽中
      <img
        slot="center"
        src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg"
        alt=""
      />
      //放入footer插槽中
      <a slot="footer" href="http://www.atguigu.com">更多美食</a>
    </Category>

    <Category title="游戏">
      <ul slot="center">
        <li v-for="(g, index) in games" :key="index">{{ g }}</li>
      </ul>
      <div class="foot" slot="footer">
        <a href="http://www.atguigu.com">单机游戏</a>
        <a href="http://www.atguigu.com">网络游戏</a>
      </div>
    </Category>

    <Category title="电影">
      <video
        slot="center"
        controls
        src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
      ></video>
      <template v-slot:footer>
        <!-- 两种写法,但 v-slot:footer只能用在template标签中-->
        <div class="foot">
          <a href="http://www.atguigu.com">经典</a>
          <a href="http://www.atguigu.com">热门</a>
          <a href="http://www.atguigu.com">推荐</a>
        </div>
        <h4>欢迎前来观影</h4>
      </template>
    </Category>
  </div>
</template>

<script>
import Category from "./components/Category";
export default {
  name: "App",
  components: { Category },
  data() {
    return {
      foods: ["火锅", "烧烤", "小龙虾", "牛排"],
      games: ["红色警戒", "穿越火线", "劲舞团", "超级玛丽"],
      films: ["《教父》", "《拆弹专家》", "《你好,李焕英》", "《与神同行》"],
    };
  },
};
</script>
<style scoped>
.container,
.foot {
  display: flex;
  justify-content: space-around;
}
h4 {
  text-align: center;
}
</style>
复制代码

4.4.4 作用域插槽

App.vue

<template>
  <div class="container">
    <Category title="游戏">
      <!-- 必须包裹template标签,scope属性标签必带,收到数据,但" "内名字随意起 -->
      <template scope="atguigu">
        <ul>
          <li v-for="(g, index) in atguigu.games" :key="index">{{ g }}</li>
        </ul>
      </template>
    </Category>

    <Category title="游戏">
      <template scope="{ games }">
        <!-- 解构赋值 -->
        <ol>
          <li style="color: red" v-for="(g, index) in games" :key="index">
            {{ g }}
          </li>
        </ol>
      </template>
    </Category>

    <Category title="游戏">
      <template slot-scope="atguigu">
        <!--slot-scope是新的API,作用与scope一样 -->
        <h4 v-for="(g, index) in atguigu.games" :key="index">{{ g }}</h4>
      </template>
    </Category>
  </div>
</template>

<script>
import Category from "./components/Category";
export default {
  name: "App",
  components: { Category },
};
</script>

<style scoped>
.container,
.foot {
  display: flex;
  justify-content: space-around;
}
h4 {
  text-align: center;
}
</style>

复制代码

Category

<template>
	<div class="category">
		<h3>{{title}}分类</h3>
		<slot :games="games" msg="hello">我是默认的一些内容</slot>
	</div>
</template>

<script>
	export default {
		name:'Category',
		props:['title'],
		data() {
			return {
				games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
			}
		},
	}
</script>

<style scoped>
	.category{
		background-color: skyblue;
		width: 200px;
		height: 300px;
	}
	h3{
		text-align: center;
		background-color: orange;
	}
	video{
		width: 100%;
	}
	img{
		width: 100%;
	}
</style>

作者:芒果炒香菜链接:https://juejin.cn/post/6997406733341556750来源:稀土掘金著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

六、vue-router

6.1相关理解

image.png

6.1.1vue-router的理解:

vue的一个插件库,专门用来实现SPA应用

6.1.2对SPA应用的理解

1.单页Web应用(singlepagewebapplication,SPA)。
2.整个应用只有一个完整的页面。
3.点击页面中的导航链接不会刷新页面,只会做页面的局部更新。
4.数据需要通过ajax请求获取。

6.1.3路由的理解

1.什么是路由?
  1. 理解: 一个路由(route)就是一组映射关系(key - value),多个路由需要路由器(router)进行管理。
  2. 前端路由:key是路径,value可能是function或component(组件)。

image.png

2.路由分类
1.后端路由:

1)理解:value是function,用于处理客户端提交的请求。
2)工作过程:服务器接收到一个请求时,根据请求路径找到匹配的函数来处理请求,返回响应数据。

2.前端路由:

1)理解:value是component,用于展示页面内容。
2)工作过程:当浏览器的路径改变时,对应的组件就会显示。

6.2.基本使用

Vue路由随手案例

  1. 安装vue-router,命令:npm i vue-router
  2. 应用插件:Vue.use(VueRouter)
  3. 编写router配置项:

index.js

//引入VueRouter
import VueRouter from 'vue-router'
//引入Luyou 组件
import About from '../components/About'
import Home from '../components/Home'

//创建router实例对象,去管理一组一组的路由规则
const router = new VueRouter({
	routes:[
		{
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home
		}
	]
})

//暴露router
export default router
  1. 实现切换(active-class:路由激活,可配置高亮样式,放在多个路由跳转之中,谁被选中active就出现在哪个链接的css样式中)

    <router-link active-class="active" to="/about">About</router-link>
    //转换成a标签
    
  2. 指定展示位置

    <router-view></router-view>
    

6.3.几个注意点

  1. 路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹。
  2. 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
  3. 每个组件都有自己的$route属性,里面存储着自己的路由信息。
  4. 整个应用只有一个router,可以通过组件的$router属性获取到。

6.4 多级路由(嵌套路由)

Vue路由随手案例

  1. 配置路由规则,使用children配置项:

    routes:[
    	{
    		path:'/about',
    		component:About,
    	},
    	{
    		path:'/home',
    		component:Home,
    		children:[ //通过children配置子级路由
    			{
    				path:'news', //此处一定不要写:/news
    				component:News
    			},
    			{
    				path:'message',//此处一定不要写:/message
    				component:Message
    			}
    		]
    	}
    ]
    
  2. 跳转(要写完整路径):

    <router-link to="/home/news">News</router-link>
    

6.5 路由的query参数

Vue路由随手案例

  1. 传递参数

    <!-- 跳转并携带query参数,to的字符串写法 -->
         //注意to前面要用v-bind绑定将其转化为js解析,然后加``将其变为模板字符串,然后里面可以${}
     <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>
    				
    <!-- 跳转并携带query参数,to的对象写法 -->
    <router-link 
    	:to="{
    		path:'/home/message/detail',
    		query:{
    		 id:m.id,
     	title:m.title
    		}
    	}"
    >跳转</router-link>
    
  2. 接收参数:

    $route.query.id
    $route.query.title
    

6.6 命名路由

  1. 作用:可以简化路由的跳转。

  2. 如何使用

    1. 给路由命名:

      {
      	path:'/demo',
      	component:Demo,
      	children:[
      		{
      			path:'test',
      			component:Test,
      			children:[
      				{
                          name:'xiangqing',//给路由命名
      					path:'welcome',
      					component:Hello,
      				}
      			]
      		}
      	]
      }
      
    2. 简化跳转:

      <!--简化前,需要写完整的路径 -->
      <router-link to="/demo/test/welcome">跳转</router-link>
      
      <!--简化后,直接通过名字跳转 -->
      <router-link :to="{name:xiangqing'}">跳转</router-link>
      
      <!--简化前,需要写完整的路径 -->
      <router-link
          :to="{
            path: '/home/message/detail',
            query: {
              id: m.id,
              title: m.title,
            },
          }"
        >
          {{ m.title }}
        </router-link>
      
      <!--简化写法配合传递参数 -->
      <router-link 
          :to="{
                name:'xiangqing',
                query:{
                        id:m.id,
                        title:m.title
                }
        }">
                {{m.title}}
        </router-link>
      

6.7 路由的params参数

Vue路由随手案例

1. 配置路由,声明接收params参数

{
	path:'/home',
	component:Home,
	children:[
		{
			path:'news',
			component:News
		},
		{
			component:Message,
			children:[
				{
					name:'xiangqing',
					path:'detail/:id/:title', //使用占位符声明接收params参数
					component:Detail
				}
			]
		}
	]
}

2. 传递参数

<!-- 跳转并携带params参数,to的字符串写法 -->
<router-link :to="/home/message/detail/666/你好">跳转</router-link>
				
<!-- 跳转并携带params参数,to的对象写法 -->
<router-link 
	:to="{
		name:'xiangqing',
		params:{
		   id:666,
                title:'你好'
		}
	}"
>跳转</router-link>

特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!

3. 接收参数:

$route.params.id
$route.params.title
复制代码

6.8 路由的props配置

Vue路由随手案例 作用:让路由组件更方便的收到参数

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

	//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
	// props:{a:900}

	//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
	// props:true
	
	//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
	props($route) {
		return {
			id: $route.query.id,
			title: $route.query.title,
		}
	}
}
复制代码

6.9``的replace属性

  1. 作用:控制路由跳转时操作浏览器历史记录的模式
  2. 浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
  3. 如何开启replace模式:News
  <router-link
            replace class="list-group-item" active-class="active" to="/about">About</router-link>
复制代码

6.10 编程式路由导航

Vue路由随手案例

  1. 作用:不借助实现路由跳转,让路由跳转更加灵活

  2. 具体编码:

    //$router的两个API
    this.$router.push({
    	name:'xiangqing',
    		params:{
    			id:xxx,
    			title:xxx
    		}
    })
    
    this.$router.replace({
    	name:'xiangqing',
    		params:{
    			id:xxx,
    			title:xxx
    		}
    })
    this.$router.forward() //前进
    this.$router.back() //后退
    this.$router.go() //可前进也可后退
    复制代码
    

image.png

6.11 缓存路由组件

  1. 作用:让不展示的路由组件保持挂载,不被销毁。
  2. 具体编码:
/*缓存由当前<router-view></router-view>展示的所有组件,即哪个组件需要被缓存,则找其父组件中的
<router-view></router-view>加上<keep-alive></keep-alive>*/
<keep-alive>
     <router-view></router-view>
</keep-alive>
复制代码
/*
include放的是组件名,表明缓存当前组件,当其不展示时也不会被销毁。如果不加include则缓存
<router-view></router-view>中展示的所有组件
*/
<!-- 缓存一个路由组件 -->
<keep-alive include="News"> 
    <router-view></router-view>
</keep-alive>
<!-- 缓存多个路由组件 -->
 <keep-alive :include="['News','Message']"> 
        <router-view></router-view>
 </keep-alive>

6.12 两个新的生命周期钩子

  1. 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
  2. 具体名字:
    1. activated路由组件被激活时触发。
    2. deactivated路由组件失活时触发。

在News组件中

<template>
	<ul>
		<li :style="{opacity}">欢迎学习Vue</li>
		<li>news001 <input type="text"></li>
		<li>news002 <input type="text"></li>
		<li>news003 <input type="text"></li>
	</ul>
</template>

<script>
	export default {
		name:'News',
		data() {
			return {
				opacity:1
			}
		},
		/* beforeDestroy() {
			console.log('News组件即将被销毁了')
			clearInterval(this.timer)
		}, */
		/* mounted(){
			this.timer = setInterval(() => {
				console.log('@')
				this.opacity -= 0.01
				if(this.opacity <= 0) this.opacity = 1
			},16)
		}, */
		activated() {
			console.log('News组件被激活了')
			this.timer = setInterval(() => {
				console.log('@')
				this.opacity -= 0.01
				if(this.opacity <= 0) this.opacity = 1
			},16)
		},
		deactivated() {
			console.log('News组件失活了')
			clearInterval(this.timer)
		},
	}
</script>

6.13 路由守卫

  1. 作用:对路由进行权限控制
  2. 分类:全局守卫、独享守卫、组件内守卫
  3. 全局守卫:

index.js

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
const router = new VueRouter({
 routes: [
 	{
 		name: 'guanyu',
 		path: '/about',
 		component: About,
 		meta: { title: '关于' }
 	},
 	{
 		name: 'zhuye',
 		path: '/home',
 		component: Home,
 		meta: { title: '主页' },
 		children: [
 			{
 				name: 'xinwen',
 				path: 'news',
 				component: News,
 				meta: { isAuth: true, title: '新闻' }
 			},
 			{
 				name: 'xiaoxi',
 				path: 'message',
 				component: Message,
 				meta: { isAuth: true, title: '消息' },
 				children: [
 					{
 						name: 'xiangqing',
 						path: 'detail',
 						component: Detail,
 						meta: { isAuth: true, title: '详情' },
 						//props的第三种写法,值为函数
 						props($route) {
 							return {
 								id: $route.query.id,
 								title: $route.query.title,
 							}
 						}

 					}
 				]
 			}
 		]
 	}
 ]
})

//全局前置守卫:初始化时执行、每次路由切换前执行
router.beforeEach((to,from,next)=>{
	console.log('beforeEach',to,from)
	if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
		if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则
			next() //放行
		}else{
			alert('暂无权限查看')
			// next({name:'guanyu'})
		}
	}else{
		next() //放行
	}
})

//全局后置守卫:初始化时执行、每次路由切换后执行
router.afterEach((to,from)=>{
	console.log('afterEach',to,from)
	if(to.meta.title){ 
		document.title = to.meta.title //修改网页的title
	}else{
		document.title = 'vue_test'
	}
})
复制代码
  1. 独享守卫:

index.js

 {
         name:'xinwen',
         path:'news',
         component:News,
         meta:{isAuth:true,title:'新闻'},
         //当前路由所独享的,可以和全局后置路由守卫配合使用
         beforeEnter: (to, from, next) => {
                 console.log('独享路由守卫',to,from)
                 if(to.meta.isAuth){ //判断是否需要鉴权
                         if(localStorage.getItem('school')==='atguigu'){
                                 next()
                         }else{
                                 alert('学校名不对,无权限查看!')
                         }
                 }else{
                         next()
                 }
         }
 },
复制代码
  1. 组件内守卫:

index.js

    {
                name:'guanyu',
                path:'/about',
                component:About,
                meta:{isAuth:true,title:'关于'}
        },
复制代码

在需要配置路由守卫的组件内配置,不是在index.js中

 //通过路由规则,进入该组件时被调用
 	beforeRouteEnter (to, from, next) {
 		console.log('About--beforeRouteEnter',to,from)
 		if(to.meta.isAuth){ //判断是否需要鉴权
 			if(localStorage.getItem('school')==='atguigu'){
 				next()
 			}else{
 				alert('学校名不对,无权限查看!')
 			}
 		}else{
 			next()
 		}
 	},

 	//通过路由规则,离开该组件时被调用
 	beforeRouteLeave (to, from, next) {
 		console.log('About--beforeRouteLeave',to,from)
 		next()
 	}
复制代码

6.14 路由器的两种工作模式

  1. 对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值。
  2. hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。
  3. hash模式:
    1. 地址中永远带着#号,不美观 。
    2. 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
    3. 兼容性较好。
  4. history模式:
    1. 地址干净,美观 。
    2. 兼容性和hash模式相比略差。
    3. 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。
const router =  new VueRouter({
	mode:'history', // 配置history,默认是hash。
	routes:[
		{
			name:'guanyu',
			path:'/about',
			component:About,
			meta:{isAuth:true,title:'关于'}
		},
		]
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值