Vue2学习之第六、七章——vue-router与ElementUI组件库

news2024/10/7 18:27:39

路由

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

1.基本使用

  1. 安装vue-router,命令:npm i vue-router

  2. 应用插件(在main.js中):

    // 引入Vue
    import Vue from 'vue'
    // 引入所有组件的父组件App
    import App from './App'
    //引入VueRouter
    import VueRouter from 'vue-router'
    // 引入路由器(在new Vue中router赋值)
    import router from './router'
    
    // 关闭生产提示
    Vue.config.productionTip = false
    // 应用插件
    Vue.use(VueRouter)
    
    // 创建vm
    new Vue({
        // el:'#app',
        render: h => h(App),
        router:router
    }).$mount('#app')
    
  3. 编写router配置项(新建一个js文件,引入到main.js中Vue中的router):

    //引入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
    
  4. (替换a标签)实现切换(active-class可配置高亮样式,to中为第3步中路由的path)

    <div class="list-group">
      <!-- 原始html中我们使用a标签实现页面的跳转 -->
      <!-- <a class="list-group-item active" href="./about.html">About</a>
      <a class="list-group-item" href="./home.html">Home</a> -->
    
      <!-- Vue中借助router-link标签实现路由的切换 -->
      <router-link class="list-group-item" active-class="active" to="/about">About</router-link>
      <router-link class="list-group-item" active-class="active" to="/home">Home</router-link>
    </div>
    
  5. 指定展示位置

    <!-- 指定组件的呈现位置 -->
    <router-view></router-view>
    
  6. 举例

    <template>
      <div>
        <div class="row">
          <div class="col-xs-offset-2 col-xs-8">
            <div class="page-header"><h2>Vue Router Demo</h2></div>
          </div>
        </div>
        <div class="row">
          <div class="col-xs-2 col-xs-offset-2">
            <div class="list-group">
             <!-- 原始html中我们使用a标签实现页面的跳转 -->
              <!-- <a class="list-group-item active" href="./about.html">About</a>
              <a class="list-group-item" href="./home.html">Home</a> -->
    
              <!-- Vue中借助router-link标签实现路由的切换 -->
              <router-link class="list-group-item" active-class="active" to="/about">About</router-link>
              <router-link class="list-group-item" active-class="active" to="/home">Home</router-link>
            </div>
          </div>
          <div class="col-xs-6">
            <div class="panel">
              <div class="panel-body">
                <!-- 指定组件的呈现位置 -->
                <router-view></router-view>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    

2.几个注意点

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

3.多级路由(多级路由)

  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>
    

4.路由的query参数

  1. 传递参数

    <!-- 跳转并携带query参数,to的字符串写法 -->
    <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link>
    				
    <!-- 跳转并携带query参数,to的对象写法 -->
    <router-link 
    	:to="{
    		path:'/home/message/detail',
    		query:{
    		   id:666,
                title:'你好'
    		}
    	}"
    >跳转</router-link>
    
  2. 接收参数:

     <template>
     	<ul>
     		<li>消息编号:{{ this.$route.query.id }}</li>
     		<li>消息标题:{{ this.$route.query.title }}</li>
     	</ul>
     </template>
    

5.命名路由

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

  2. 如何使用

    1. 给路由命名:

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

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

6.路由的params参数

  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>
    <!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link> -->
    				
    <!-- 跳转并携带params参数,to的对象写法 -->
    <router-link 
    	:to="{
    		name:'xiangqing',
    		params:{
    		   id:666,
                title:'你好'
    		}
    	}"
    >跳转</router-link>
    

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

  3. 接收参数:

     <template>
        <ul>
     	    <li>消息编号:{{ this.$route.params.id }}</li>
     	    <li>消息标题:{{ this.$route.params.title }}</li>
        </ul>
     </template>
    

7.路由的props配置

​ 作用:让路由组件更方便的收到参数

{
	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
		}
	}
}

8.<router-link>的replace属性

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

9.编程式路由导航

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

  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() //可前进也可后退,在里面填写正数前进,负数后退
    

10.缓存路由组件

  1. 作用:让不展示的路由组件保持挂载,不被销毁。

  2. 具体编码:

     <!-- 缓存多个路由组件 -->
     <!-- <keep-alive :include="['News','Message']">
     	<router-view></router-view>
     </keep-alive> -->
     
     <!-- 缓存一个路由组件 -->
     <keep-alive include="News">
     	<router-view></router-view>
     </keep-alive>
    

11.两个新的生命周期钩子

  1. 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。

  2. 具体名字:

    1. activated路由组件被激活时触发。
    2. deactivated路由组件失活时触发。
  3. 当你使用了缓存路由组件之后,但是你却想将你定义的定时器等功能给销毁时,即可使用activateddeactivated

    activated(){
         console.log('News组件激活了');
         this.times = setInterval(() => {
            console.log('@');
            this.opacity -= 0.01
            if(this.opacity <= 0) this.opacity = 1
         }, 16)
      },
    deactivated(){
       console.log('News组件失活了');
       clearInterval(this.times)
    }
    

12.路由守卫

  1. 作用:对路由进行权限控制

  2. 分类:全局守卫、独享守卫、组件内守卫

  3. 全局守卫:

    //全局前置守卫:初始化时执行、每次路由切换前执行
    const router = new VueRouter({
     ......
     })
    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'
    	}
    })
    export default router
    
  4. 独享守卫:

    const router = new VueRouter({
     	mode:'hash',
     // mode:'history',
     routes:[
         {
     		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') === '张三学院') {
     					next() //放行
     				}else {
     					alert('学校名不对,无权查看!')
     				}
     			}else {
     				next()
     			}
     		})
         },
     ]
    })
    
  5. 组件内守卫(在所需守卫的组件添加即可):

      <script>
         export default {
           name:'About',
     
           //  通过路由规则,进入该组件时被调用
           beforeRouteEnter (to, from, next) {
              console.log('About--beforeRouteEnter',to,from);
              if(to.meta.isAuth) { //判断是否需要权限
                 if(localStorage.getItem('school') === '张三学院') {
                       next() //放行
                 }else {
                       alert('学校名不对,无权查看!')
                 }
              }else {
                 next()
              }
           },
           
           //  通过路由规则,离开该组件时被调用
           beforeRouteLeave (to, from, next) {
              console.log('About--beforeRouteLeave',to,from);
              next()
           }
         }
      </script>
    

13.路由器的两种工作模式

  1. 对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值。

  2. hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。

  3. hash模式:

    1. 地址中永远带着#号,不美观 。
    2. 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
    3. 兼容性较好。
  4. history模式:

    1. 地址干净,美观 。
    2. 兼容性和hash模式相比略差。
    3. 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。
  5. 在路由里设置即可

    const router = new VueRouter({
    	mode:'hash',
        // mode:'history',
    	......
    })
    

ElementUI组件库

ElementUI地址:https://element.eleme.cn/#/zh-CN/component/installation

按需引入

  1. main.js文件中
    // 引入Vue
    import Vue from 'vue'
    // 引入所有组件的父组件App
    import App from './App'
    // 按需引入(使用那个引入那个)
    import { Button, Row, DatePicker } from 'element-ui';
    // 关闭生产提示
    Vue.config.productionTip = false
    //应用ElementUI
    Vue.component(Button.name, Button);
    Vue.component('el-row', Row);
    Vue.component('el-date-picker', DatePicker);
    // 创建vm
    new Vue({
        // el:'#app',
        render: h => h(App),
    }).$mount('#app')	
    
  2. babel.config.js
    module.exports = {
      presets: [
        '@vue/cli-plugin-babel/preset',
        ["@babel/preset-env", { "modules": false }]
      ],
      "plugins": [
        [
          "component",
          {
            "libraryName": "element-ui",
            "styleLibraryName": "theme-chalk"
          }
        ]
      ]
    }
    
  3. 之后即可在组件中使用按需引入的组件即可
    <template>
      <div>
    		<button>原生的按钮</button>
    		<input type="text">
    		<el-row>
    			<el-button>默认按钮</el-button>
    			<el-button type="primary">主要按钮</el-button>
    			<el-button type="success">成功按钮</el-button>
    			<el-button type="info">信息按钮</el-button>
    			<el-button type="warning">警告按钮</el-button>
    			<el-button type="danger">危险按钮</el-button>
    		</el-row>
    		<el-date-picker
          type="date"
          placeholder="选择日期">
        </el-date-picker>
    		<el-row>
    			<el-button icon="el-icon-search" circle></el-button>
    			<el-button type="primary" icon="el-icon-s-check" circle></el-button>
    			<el-button type="success" icon="el-icon-check" circle></el-button>
    			<el-button type="info" icon="el-icon-message" circle></el-button>
    			<el-button type="warning" icon="el-icon-star-off" circle></el-button>
    			<el-button type="danger" icon="el-icon-delete" circle></el-button>
    		</el-row>
      </div>
    </template>
    

按需引入报错

  1. 如果根据ElementUI组件库的快速上手一步一步引入,将会报以下错误
    在这里插入图片描述
  2. babel.config.js中将["es2015", { "modules": false }]修改为["@babel/preset-env", { "modules": false }]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1411685.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

springboot快速写接口

1. 建proj形式 name会变成文件夹的名字&#xff0c;相当于你的项目名称 基础包 2. 基础依赖 3. 配置数据库 这里要打开mysql&#xff0c;并且创建数据库 方法&#xff1a; 安装好数据库&#xff0c;改好账号密码用navicat来建表和账号配置properties.yml文件即可 4.用res…

读AI3.0笔记07_游戏与推理

1. 始于游戏&#xff0c;不止于游戏 1.1. 开发超人类的游戏程序并不是人工智能的最终目的 1.2. AlphaGo所有的版本除了下围棋&#xff0c;其他什么也不会 1.2.1. 其最通用的版本AlphaGo Zero也一样 1.3. 这些游戏程序中没有一个能够将其在一款游戏中学到的知识迁移到其他游…

引领未来:云原生在产品、架构与商业模式中的创新与应用

文章目录 一、云原生产品创新二、云原生架构设计三、云原生商业模式变革《云原生落地 产品、架构与商业模式》适读人群编辑推荐内容简介目录 随着云计算技术的不断发展&#xff0c;云原生已经成为企业数字化转型的重要方向。接下来将从产品、架构和商业模式三个方面&#xff0c…

融合创新:传统企业数字化转型的业务、战略、操作和文化变革

引言 随着科技的不断演进&#xff0c;传统企业正站在数字化转型的前沿&#xff0c;这是一场前所未有的全面变革之旅。数字化已经超越了单纯的技术升级&#xff0c;成为企业保持竞争力、开创未来的必然选择。本文将引领您探讨&#xff0c;迈向数字化未来的传统企业全面数字化转…

回归预测 | Matlab基于SSA-SVR麻雀算法优化支持向量机的数据多输入单输出回归预测

回归预测 | Matlab基于SSA-SVR麻雀算法优化支持向量机的数据多输入单输出回归预测 目录 回归预测 | Matlab基于SSA-SVR麻雀算法优化支持向量机的数据多输入单输出回归预测预测效果基本描述程序设计参考资料 预测效果 基本描述 1.Matlab基于SSA-SVR麻雀算法优化支持向量机的数据…

解密:消息中间件的选择与使用:打造高效通信枢纽

目录 第一章&#xff1a;消息中间件介绍 1.1 什么是消息中间件 1.2 消息中间件的作用 1.3 消息中间件的分类 第二章&#xff1a;消息中间件的选择标准 2.1 性能 2.2 可靠性 2.3 可扩展性 2.4 易用性 2.5 社区支持 2.6 成本 第三章&#xff1a;常见的消息中间件对比…

docker 网络及如何资源(CPU/内存/磁盘)控制

安装Docker时&#xff0c;它会自动创建三个网络&#xff0c;bridge&#xff08;创建容器默认连接到此网络&#xff09;、 none 、host docker网络模式 Host 容器与宿主机共享网络namespace&#xff0c;即容器和宿主机使用同一个IP、端口范围&#xff08;容器与宿主机或其他使…

[ACM学习] 进制转换

进制的本质 本质是每一位的数位上的数字乘上这一位的权重 将任意进制转换为十进制 原来还很疑惑为什么从高位开始&#xff0c;原来从高位开始的&#xff0c;可以被滚动地乘很多遍。 将十进制转换为任意进制

VsCode提高生产力的插件推荐-持续更新中

别名路径跳转 自定义配置// 文件名别名跳转 "alias-skip.mappings": { "~/": "/src", "views": "/src/views", "assets": "/src/assets", "network": "/src/network", "comm…

CNN卷积理解

1 卷积的步骤 1 过滤器&#xff08;卷积核&#xff09;&#xff08;Filter或Kernel&#xff09;&#xff1a; 卷积层使用一组可学习的过滤器来扫描输入数据&#xff08;通常是图像&#xff09;。每个过滤器都是一个小的窗口&#xff0c;包含一些权重&#xff0c;这些权重通过训…

Supervised Contrastive 损失函数详解

有什么不对的及时指出&#xff0c;共同学习进步。(●’◡’●) 有监督对比学习将自监督批量对比方法扩展到完全监督设置&#xff0c;能够有效地利用标签信息。属于同一类的点簇在嵌入空间中被拉到一起&#xff0c;同时将来自不同类的样本簇推开。这种损失显示出对自然损坏很稳…

支付宝AES如何加密

继之前给大家介绍了 V3 加密解密的方法之后&#xff0c;今天给大家介绍下支付宝的 AES 加密。 注意&#xff1a;以下说明均在使用支付宝 SDK 集成的基础上&#xff0c;未使用支付宝 SDK 的小伙伴要使用的话老老实实从 AES 加密原理开始研究吧。 什么是AES密钥 AES 是一种高级加…

k8s实例

k8s实例举例 &#xff08;1&#xff09;Kubernetes 区域可采用 Kubeadm 方式进行安装。 &#xff08;2&#xff09;要求在 Kubernetes 环境中&#xff0c;通过yaml文件的方式&#xff0c;创建2个Nginx Pod分别放置在两个不同的节点上&#xff0c;Pod使用动态PV类型的存储卷挂载…

虚幻UE 插件-像素流送实现和优化

本笔记记录了像素流送插件的实现和优化过程。 UE version&#xff1a;5.3 文章目录 一、像素流送二、实现步骤1、开启像素流送插件2、设置参数3、打包程序4、打包后的程序进行像素流参数设置5、下载NodeJS6、下载信令服务器7、对信令服务器进行设置8、启动像素流送 三、优化1、…

路飞项目--03

总页面 二次封装Response模块 # drf提供的Response&#xff0c;前端想接收到的格式 {code:xx,msg:xx} 后端返回&#xff0c;前端收到&#xff1a; APIResponse(tokneasdfa.asdfas.asdf)---->{code:100,msg:成功,token:asdfa.asdfas.asdf} APIResponse(code101,msg用户不存…

数据结构排序算详解(动态图+代码描述)

目录 1、直接插入排序&#xff08;升序&#xff09; 2、希尔排序&#xff08;升序&#xff09; 3、选择排序&#xff08;升序&#xff09; 方式一&#xff08;一个指针&#xff09; 方式二&#xff08;两个指针&#xff09; 4、堆排序&#xff08;升序&#xff09; 5、冒…

精酿啤酒:啤酒花的选择与处理方法

啤酒花在啤酒的酿造过程中起着重要的作用&#xff0c;它不仅赋予啤酒与众不同的苦味和香味&#xff0c;还为啤酒的稳定性提供了帮助。对于Fendi Club啤酒来说&#xff0c;啤酒花的选择和处理方法更是重要。下面&#xff0c;我们将深入探讨Fendi Club啤酒在啤酒花的选择和处理方…

一文详解C++拷贝构造函数

文章目录 引入一、什么是拷贝构造函数&#xff1f;二、什么情况下使用拷贝构造函数&#xff1f;三、使用拷贝构造函数需要注意什么&#xff1f;四、深拷贝和浅拷贝浅拷贝深拷贝 引入 在现实生活中&#xff0c;可能存在一个与你一样的自己&#xff0c;我们称其为双胞胎。 相当…

【并发编程】 synchronized的普通方法,静态方法,锁对象,锁升级过程,可重入锁,非公平锁

目录 1.普通方法 2.静态方法 3.锁对象 4.锁升级过程 5.可重入的锁 6.不公平锁 非公平锁的 lock 方法&#xff1a; 1.普通方法 将synchronized修饰在普通同步方法&#xff0c;那么该锁的作用域是在当前实例对象范围内,也就是说对于 SyncDemosdnewSyncDemo();这一个实例对象…

el-table 动态渲染多级表头;一级表头根据数据动态生成,二级表头固定

一、表格需求&#xff1a; 实现一个动态表头&#xff0c;一级表头&#xff0c;根据数据动态生成&#xff0c;二级表头固定&#xff0c;每列的数据不一样&#xff0c;难点在于数据的处理。做这种表头需要两组数据&#xff0c;一组数据是实现表头的&#xff0c;另一组数据是内容…