美文网首页
02尚硅谷B站课程Vue2.0+Vue3.0笔记-VUE2进阶

02尚硅谷B站课程Vue2.0+Vue3.0笔记-VUE2进阶

作者: scckele | 来源:发表于2024-08-06 18:37 被阅读0次

VUE2进阶

分析脚手架

说明

1.Vue 脚手架是 Vue 官方提供的标准化开发工具(开发平台)。
2.最新的版本是 4.x
3.文档: https://cli.vuejs.org/zh/

安装步骤

第一步(仅第一次执行):全局安装@vue/cli。

npm install -g @vue/cli

vue --version

第二步:切换到你要创建项目的目录,然后使用命令创建项目

vue create xxxx

第三步:启动项目

npm run serve

编译

npm run build

npm run lint

备注:

  1. 如出现下载缓慢请配置 npm 淘宝镜像:npm config set registry https://registry.npm.taobao.org
  2. Vue 脚手架隐藏了所有 webpack 相关的配置,若想查看具体的 webpakc 配置,
    请执行:vue inspect > output.js

模板项目的结构

    ├── node_modules 
    ├── public
    │   ├── favicon.ico: 页签图标
    │   └── index.html: 主页面
    ├── src
    │   ├── assets: 存放静态资源
    │   │   └── logo.png
    │   │── component: 存放组件
    │   │   └── HelloWorld.vue
    │   │── App.vue: 汇总所有组件
    │   │── main.js: 入口文件
    ├── .gitignore: git版本管制忽略的配置
    ├── babel.config.js: babel的配置文件
    ├── package.json: 应用包配置文件 
    ├── README.md: 应用描述文件
    ├── package-lock.json:包版本控制文件
    ├── vue.config.js:vue脚手架配置

vue.config.js配置文件

  1. 使用vue inspect > output.js可以查看到Vue脚手架的默认配置。
  2. 使用vue.config.js可以对脚手架进行个性化定制,详情见:https://cli.vuejs.org/zh

render解析-关于不同版本的Vue

src/main.js解释

/* 
    该文件是整个项目的入口文件
*/
//引入Vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//关闭vue的生产提示
Vue.config.productionTip = false

//new Vue({
//  render: h => h(App),
//}).$mount('#app')


//创建Vue实例对象---vm
new Vue({
    el:'#app',  //$mount('#app')
    /* 
    //原来写法 =》不可用
    //因为调用的残缺版本vue,template不能使用
    template:`<h1>你好啊</h1>`, 
     components:{App},
    */

    //探索render作用与特点
    //render(a){ //此处的a是一个函数
    //   console.log(typeof a)  //打印function
    //   return null
    //  }

    //render(createElement){
    //  return createElement('h1','你好啊')
    //}

    // render:q=> q('h1','你好啊') //render没有用到this,可以用箭头函数

    //render函数完成了这个功能:将App组件放入容器中
    render: h => h (App),//app包含了所有的页面组件,传进去render负责解析

})

参考以前的记录:<span data-type="text">el与data的两种写法</span>

关于不同版本的Vue:
1.vue.js与vue.runtime.xxx.js的区别:
(1).vue.js是完整版的Vue,包含:核心功能+模板解析器。
(2).vue.runtime.xxx.js是运行版的Vue,只包含:核心功能;没有模板解析器。
2.因为vue.runtime.xxx.js没有模板解析器,所以不能使用template配置项,需要使用render函数接收到的createElement函数去指定具体内容。

此时引入的VUE版本是vue.runtime.js

ref 属性

<template>//App.vue
    <div>
        <h1 v-text="msg" ref="title"></h1>
        <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button>
        <School ref="sch"/>
    </div>
</template>

<script>
    //引入School组件
    import School from './components/School'

    export default {
        name:'App',
        components:{School},
        data() {
            return {
                msg:'欢迎学习Vue!'
            }
        },
        methods: {
            showDOM(){
                console.log(this.$refs.title) //真实DOM元素
                console.log(this.$refs.btn) //真实DOM元素
                console.log(this.$refs.sch) //School组件的实例对象(vc)
            }
        },
    }
</script>

  1. 被用来给元素或子组件注册引用信息(id的替代者)

  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)

  3. 使用方式:

    1. 打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    2. 获取:this.$refs.xxx

props配置项

<template>//Student.vue
    <div>
        <h1>{{msg}}</h1>
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <h2>学生年龄:{{myAge+1}}</h2>
        <button @click="updateAge">尝试修改收到的年龄</button>
    </div>
</template>

<script>
    export default {
        name:'Student',
        data() {
            console.log(this)
            return {
                msg:'我是一个尚硅谷的学生',
                myAge:this.age //复制props的内容到data中一份,然后去修改data中的数据
            }
        },
        methods: {
            updateAge(){
                this.myAge++
            }
        },
        //简单声明接收
        // props:['name','age','sex'] 

        //接收的同时对数据进行类型限制
        /* props:{
            name:String,
            age:Number,
            sex:String
        } */

        //接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
        props:{
            name:{
                type:String, //name的类型是字符串
                required:true, //name是必要的
            },
            age:{
                type:Number,
                default:99 //默认值
            },
            sex:{
                type:String,
                required:true
            }
        }
    }
</script>
<template>//App.vue
//传入值,用props接收
//:age="18"  加冒号为动态绑定,“18”会被解析成表达式
//不加冒号,则传的是字符串“18”,而我们要的是number
//也可以直接写age=18
    <div>
        <Student name="李四" sex="女" :age="18"/> 
    </div>
</template>

<script>
    import Student from './components/Student'

    export default {
        name:'App',
        components:{Student}
    }
</script>

注意区分:js表达式 和 js代码(语句)
1.表达式:一个表达式会产生一个值,可以放在任何一个需要值的地方:
(1)a
(2)a+b
(3)demo(1)
(4)x === y ? 'a' : 'b'
2.js代码(语句)
(1)if(){}
(2)for(){}

  1. 功能:让组件接收外部传过来的数据

  2. 传递数据:<Demo name="xxx"/>

  3. 接收数据:

    1. 第一种方式(只接收):props:['name']

    2. 第二种方式(限制类型):props:{name:String}

    3. 第三种方式(限制类型、限制必要性、指定默认值):

      props:{
          name:{
          type:String, //类型
          required:true, //必要性
          default:'老王' //默认值
          }
      }
      

    备注:

    1、声明接收字段时不要无中生有或者画蛇添足

    2、接收的props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据myAge:this.age

    3、传递数据时字段名禁用关键字 key ref等

    4、它优先级比较高

mixin(混入)

  1. 功能:可以把多个组件共用的配置提取成一个混入对象

  2. 使用方式:
    第一步定义混合:

    export const xxx{
        data(){....},
        methods:{....}
        ....
    }
    

    第二步使用混入:
    全局混入:Vue.mixin(xxx) 写于main.js
    局部混入:mixins:['xxx'] 写于相关组件

插件

  1. 功能:用于增强Vue ,本质是一个对象

  2. 本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。

  3. 适合N多全局性设置,控制实例

  4. 定义插件:

    对象.install = function (Vue, options) {
        // 1. 添加全局过滤器
        Vue.filter(....)
    
        // 2. 添加全局指令
        Vue.directive(....)
    
        // 3. 配置全局混入(合)
        Vue.mixin(....)
    
        // 4. 添加实例方法(vm和vc就都能用了)
        Vue.prototype.$myMethod = function () {...}
        Vue.prototype.$myProperty = xxxx 
    }
    
  5. 使用插件:在main.js中Vue.use(),可以多个

scoped样式

  1. 作用:让样式在局部生效,防止冲突。
  2. 写法:<style scoped>

比如Student School组件style中都有一个demo的样式

总结TodoList案例

  1. 组件化编码流程:
    (1)拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突,在拆样式。
    (2)实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:
    1)一个组件在用:放在组件自身即可。
    2)一些组件在用:放在他们共同的父组件上(状态提升)。
    3)数据在哪,一般操作数据的增删改查就在那里
    (3)实现交互:从绑定事件开始。
  2. props适用于:
    (1)父组件 ==> 子组件 通信
    (2)子组件 ==> 父组件 通信(要求父先给子一个函数)
    即通过一个在vc上的函数实现通信
  3. 使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!
  4. props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做。

组件化编码流程(通用)

1.实现静态组件:抽取组件,使用组件实现静态页面效果

2.展示动态数据:

2.1. 数据的类型、名称是什么?

2.2. 数据保存在哪个组件?

3.交互——从绑定事件监听开始

此时,header和list兄弟组件间通信通过app组件一层层去实现

浏览器本地存储

localStorage

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>localStorage</title>
    </head>
    <body>
        <h2>localStorage</h2>
        <button onclick="saveData()">点我保存一个数据</button>
        <button onclick="readData()">点我读取一个数据</button>
        <button onclick="deleteData()">点我删除一个数据</button>
        <button onclick="deleteAllData()">点我清空一个数据</button>

        <script type="text/javascript" >
            let p = {name:'张三',age:18}

            function saveData(){
                localStorage.setItem('msg','hello!!!')
                localStorage.setItem('msg2',666)
                localStorage.setItem('person',JSON.stringify(p))
            }
            function readData(){
                console.log(localStorage.getItem('msg'))
                console.log(localStorage.getItem('msg2'))

                const result = localStorage.getItem('person')
                console.log(JSON.parse(result))

                // console.log(localStorage.getItem('msg3'))
            }
            function deleteData(){
                localStorage.removeItem('msg2')
            }
            function deleteAllData(){
                localStorage.clear()
            }
        </script>
    </body>
</html>

sessionStorage

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>sessionStorage</title>
    </head>
    <body>
        <h2>sessionStorage</h2>
        <button onclick="saveData()">点我保存一个数据</button>
        <button onclick="readData()">点我读取一个数据</button>
        <button onclick="deleteData()">点我删除一个数据</button>
        <button onclick="deleteAllData()">点我清空一个数据</button>

        <script type="text/javascript" >
            let p = {name:'张三',age:18}

            function saveData(){
                sessionStorage.setItem('msg','hello!!!')
                sessionStorage.setItem('msg2',666)
                sessionStorage.setItem('person',JSON.stringify(p))
            }
            function readData(){
                console.log(sessionStorage.getItem('msg'))
                console.log(sessionStorage.getItem('msg2'))

                const result = sessionStorage.getItem('person')
                console.log(JSON.parse(result))

                // console.log(sessionStorage.getItem('msg3'))
            }
            function deleteData(){
                sessionStorage.removeItem('msg2')
            }
            function deleteAllData(){
                sessionStorage.clear()
            }
        </script>
    </body>
</html>

总结

  1. 存储内容大小一般支持5MB左右(不同浏览器可能还不一样)

  2. 浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。

  3. 相关API:

    1. xxxxxStorage.setItem('key', 'value'); 该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。
    2. xxxxxStorage.getItem('person');
      该方法接受一个键名作为参数,返回键名对应的值。
    3. xxxxxStorage.removeItem('key');
      该方法接受一个键名作为参数,并把该键名从存储中删除。
    4. xxxxxStorage.clear()
      该方法会清空存储中的所有数据。
  4. 备注:

    1. SessionStorage存储的内容会随着浏览器窗口关闭而消失。
    2. LocalStorage存储的内容,需要手动清除才会消失。
    3. xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。
    4. JSON.parse(null)的结果依然是null。

组件的自定义事件 $refs $emit

组件的自定义事件

<template>//App.vue
    <div class="app">
        <h1>{{msg}},学生姓名是:{{studentName}}</h1>

        <!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
        <School :getSchoolName="getSchoolName"/>

        <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
        <!-- <Student @atguigu="getStudentName" @demo="m1"/> -->

        <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
        <Student ref="student" @click.native="show"/>
    </div>
</template>

<script>
    import Student from './components/Student'
    import School from './components/School'

    export default {
        name:'App',
        components:{School,Student},
        data() {
            return {
                msg:'你好啊!',
                studentName:''
            }
        },
        methods: {
            //props方法
            getSchoolName(name){
                console.log('App收到了学校名:',name)
            },
            //v-on 
            getStudentName(name,...params){
                console.log('App收到了学生名:',name,params)
                this.studentName = name
            },
            m1(){
                console.log('demo事件被触发了!')
            },
            show(){
                alert(123)
            }
        },
        mounted() {
            //绑定自定义事件
            this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件
            // this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
        },
    }
</script>

<style scoped>
    .app{
        background-color: gray;
        padding: 5px;
    }
</style>

<template>//Student.vue
    <div class="student">
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <h2>当前求和为:{{number}}</h2>
        <button @click="add">点我number++</button>
        <button @click="sendStudentlName">把学生名给App</button>
        <button @click="unbind">解绑atguigu事件</button>
        <button @click="death">销毁当前Student组件的实例(vc)</button>
    </div>
</template>

<script>
    export default {
        name:'Student',
        data() {
            return {
                name:'张三',
                sex:'男',
                number:0
            }
        },
        methods: {
            add(){
                console.log('add回调被调用了')
                this.number++
            },
            sendStudentlName(){
                //触发Student组件实例身上的atguigu事件
                this.$emit('atguigu',this.name,666,888,900)
                // this.$emit('demo')
                // this.$emit('click')
            },
            unbind(){
                this.$off('atguigu') //解绑一个自定义事件
                // this.$off(['atguigu','demo']) //解绑多个自定义事件
                // this.$off() //解绑所有的自定义事件
            },
            death(){
                this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。
            }
        },
    }
</script>

<style lang="less" scoped>
    .student{
        background-color: pink;
        padding: 5px;
        margin-top: 30px;
    }
</style>
  1. 一种组件间通信的方式,适用于:子组件 ===> 父组件

  2. 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。

  3. 实现方式

    1. 父组件中:

      给子组件绑定一个自定义事件

      <Student @atguigu="getStudentName"/>

      声明事件方法:

      getStudentName(name,...params){
          console.log('App收到了学生名:',name,params)
          this.studentName = name
      },
      

      若想让自定义事件只能触发一次,可以使用once修饰符<Student @atguigu="getStudentName"/>

    2. 子组件中

      触发方式

      <button @click="sendStudentlName">把学生名给App</button>

      触发方法

      sendStudentlName(){
          //触发Student组件实例身上的atguigu事件
          this.$emit('atguigu',this.name,666,888,900)
          // this.$emit('demo')
          // this.$emit('click')
      },
      

实现子组件给父组件传递数据的方式

  1. props方式

    1. 父组件中

      对子组件绑定或者声明:接收数据的方法

      声明:<School :getSchoolName="getSchoolName"/>

      接收数据的方法:

      getStudentName(name,...params){
          console.log('App收到了学生名:',name,params)
          this.studentName = name
      }
      
    2. 子组件中

      通过props接收这个方法props:['getSchoolName']

      通过自己内部触发sendSchoolName方法,调用父组件中声明的方法让父组件接收到数据

      <button @click="sendSchoolName">把学校名给App</button>
      -----------------------------------
      sendSchoolName(){
      this.getSchoolName(this.name)
      }
      
  2. 绑定一个自定义事件实现(<span data-type="text">实现方式</span>)

  3. ref方式

    1. 父组件中

      给子组件绑定一个ref

      <Student ref="student"/>

      接收数据的方法同一

      在mounted中绑定ref(<span data-type="text">ref 属性</span>说明)

      mounted() {
      //翻译:APP只要挂载完毕
      //就给Student组件VC上
      //当一个on事件   事件名atguigu  事件方法getStudentName 被触发时执行
          this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件
          // this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
      },
      

      若想让自定义事件只能触发一次,可以使用$once方法。

      注意:事件方法getStudentName不能在mounted()写成函数式,只能调用在父组件metheds中的方法。

      //因为vue规定那个组件触发事件,则this就是谁的vc
      //则下面这段代码虽然写在父组件中
      //但调用的this一直都是子组件的VC
      //那么为什么最后父组件却能接收到数据呢?
      //因为此时的getStudentName是写在父组件中metheds下的,
      //vue特性,只要是写在本组件中的函数式方法,内部this一定是本组件的vc,且本组件优先级最高
      //最后顺利获取数据
      mounted() {
          this.$refs.student.$on('atguigu',this.getStudentName)
      },
      
      //此时的this不是父组件的vc
      //是触发该事件的子组件的vc,下面这么写相当于还是给子组件的studentName赋值
      //父组件则还是没接收到数据
      //上面那么写就是父组件上的this
      mounted() {
          this.$refs.student.$on('atguigu',function(name,...params){
          console.log('App收到了学校名:',name,params)//能接收到数据
          this.studentName = name
          console.log(this)
          ) 
      },
      
      //换成箭头函数 也可以实现
      //因为箭头函数没有自己的this,只能外找
      //因为mounted是在父组件中,所以找到的还是父组件的VC
      mounted() {
          this.$refs.student.$on('atguigu',(name,...params)=>{
          console.log('App收到了学校名:',name,params)//能接收到数据
          this.studentName = name 
          console.log(this)//打印此时的this
          ) 
      },
      
    2. 子组件中

      触发方式同第二种方式

  4. 其他事项

    1. 绑定自定义事件:this.$refs.组件.$on('事件名',回调)

    2. 触发自定义事件:this.$emit('事件名',数据)

    3. 解绑自定义事件

      this.$off('atguigu') //解绑一个自定义事件
      this.$off(['atguigu','demo']) //解绑多个自定义事件
      this.$off() //解绑所有的自定义事件
      
    4. 组件上也可以绑定原生DOM事件,需要使用native修饰符。

      不加,则会被认作自定义事件,需要在子组件触发才会执行

      <Student ref="student" @click.native="show"/>

      methods: {
          show(){
              alert(123)
          }
      }
      
    5. 销毁了当前组件的实例VC,销毁后所有该组件实例的自定义事件全都不奏效。

      若放在VM上,则所有子组件自定义事件全都不奏效。

      methods: {
          death(){//Student组件中
              this.$destroy() 
              }
          },
      }
      
    6. 注意:通过this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中要么用箭头函数,否则this指向会出问题!

全局事件总线(GlobalEventBus)

  1. 一种组件间通信的方式,适用于任意组件间通信。

  2. 总线特点:

    1. 所有的组件能看到它
    2. 可以调用到 $on $off $emit
  3. 安装全局事件总线:main.js

    new Vue({//main.js
        ......
        beforeCreate() {
            Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
        },
        ......
    }) 
    
  4. 使用事件总线:

    1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.$bus.$on('xxxx',this.demo)
      }
      
    2. 提供数据:this.$bus.$emit('xxxx',数据)

  5. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。

消息订阅与发布(pubsub)

  1. 一种组件间通信的方式,适用于任意组件间通信。

  2. 使用步骤:

    1. 安装pubsub:npm i pubsub-js

    2. 引入: import pubsub from 'pubsub-js'

    3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息   或者箭头函数
      }
      
    4. 提供数据:pubsub.publish('xxx',数据)

    5. 最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)去取消订阅。

钩子函数 nextTick

  1. 语法:this.$nextTick(回调函数)
  2. 作用:在下一次 DOM 更新结束后执行其指定的回调。
  3. 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。

Vue封装的过度与动画

vue 动画的理解

动画样式

<template>
    <div>
        <button @click="isShow = !isShow">显示/隐藏</button>
        <transition name="hello" appear> //appear默认走一次
            <h1 v-show="isShow">你好啊!</h1>
        </transition>
    </div>
</template>

<script>
    export default {
        name:'Test',
        data() {
            return {
                isShow:true
            }
        },
    }
</script>

<style scoped>
    h1{
        background-color: orange;
    }

    .hello-enter-active{
        animation: atguigu 0.5s linear;
    }

    .hello-leave-active{
        animation: atguigu 0.5s linear reverse;
    }

    @keyframes atguigu {
        from{
            transform: translateX(-100%);
        }
        to{
            transform: translateX(0px);
        }
    }
</style>

过渡方式

<template>
    <div>
        <button @click="isShow = !isShow">显示/隐藏</button>
        <transition-group name="hello" appear>
            <h1 v-show="!isShow" key="1">你好啊!</h1>
            <h1 v-show="isShow" key="2">尚硅谷!</h1>
        </transition-group>
    </div>
</template>

<script>
    export default {
        name:'Test',
        data() {
            return {
                isShow:true
            }
        },
    }
</script>

<style scoped>
    h1{
        background-color: orange;
    }
    /* 进入的起点、离开的终点 */
    .hello-enter,.hello-leave-to{
        transform: translateX(-100%);
    }
    /* 进入的过程、离开的过程 */
    .hello-enter-active,.hello-leave-active{
        transition: 0.5s linear;
    }
    /* 进入的终点、离开的起点 */
    .hello-enter-to,.hello-leave{
        transform: translateX(0);
    }

</style>

动画库

<template>
    <div>
        <button @click="isShow = !isShow">显示/隐藏</button>
        <transition-group 
            appear
            name="animate__animated animate__bounce" 
            enter-active-class="animate__swing"
            leave-active-class="animate__backOutUp"
        >
            <h1 v-show="!isShow" key="1">你好啊!</h1>
            <h1 v-show="isShow" key="2">尚硅谷!</h1>
        </transition-group>
    </div>
</template>

<script>
    import 'animate.css'
    export default {
        name:'Test',
        data() {
            return {
                isShow:true
            }
        },
    }
</script>

<style scoped>
    h1{
        background-color: orange;
    }
</style>

理解

动态库:http://animation.style/

  1. 操作 css 的 trasition 或 animation
  2. vue 会给目标元素添加/移除特定的 class
  3. 过渡的相关类名:
  4. xxx-enter-active: 指定显示的 transition
  5. xxx-leave-active: 指定隐藏的 transition
  6. xxx-enter/xxx-leave-to: 指定隐藏时的样式

基本过渡动画的编码

  1. 在目标元素外包裹<transition name="xxx">

  2. 定义 class 样式

    1. a) 指定过渡样式: transition
    2. b) 指定隐藏时的样式: opacity/其它

总结

  1. 作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。

  2. 图示:
  3. 写法:

    1. 准备好样式:

      • 元素进入的样式:

        1. v-enter:进入的起点
        2. v-enter-active:进入过程中
        3. v-enter-to:进入的终点
      • 元素离开的样式:

        1. v-leave:离开的起点
        2. v-leave-active:离开过程中
        3. v-leave-to:离开的终点
    2. 使用<transition>包裹要过度的元素,并配置name属性:

      <transition name="hello">
          <h1 v-show="isShow">你好啊!</h1>
      </transition>
      
    3. 备注:若有多个元素需要过度,则需要使用:<transition-group>,且每个元素都要指定key值。

vue脚手架配置代理-跨域

方法一

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

devServer:{
  proxy:"http://localhost:5000"
}

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)

方法二

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

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

说明:

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

vue 项目中常用的 2 个 Ajax 库

axios

通用的 Ajax 请求库, 官方推荐,使用广泛

vue-resource

vue 插件库, vue1.x 使用广泛,官方已不维护

//main.js使用插件
Vue.use(vueResource)


searchUsers(){
    //请求前更新List的数据
    this.$bus.$emit('updateListData',{isLoading:true,errMsg:'',users:[],isFirst:false})
    this.$http.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
        response => {
            console.log('请求成功了')
            //请求成功后更新List的数据
            this.$bus.$emit('updateListData',{isLoading:false,errMsg:'',users:response.data.items})
        },
        error => {
            //请求后更新List的数据
            this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]})
        }
    )
}

插槽 slot

不使用插槽

<template>//父组件
    <div class="container">
        <Category :listData="foods"/>
        <Category :listData="games"/>
        <Category :listData="films"/>
</div>
</template>

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

默认插槽

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

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

具名插槽

<template>//父组件
    <div class="container">
        <Category title="美食" >
            <img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
            <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>
                <!-- v-slot:footer只有 </template>中才能这样写 -->
                <template v-slot:footer> 
                <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>


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

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

作用域插槽

<template>//父组件
    <div class="container">

        <Category title="游戏">
            <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="{games}">
                <h4 v-for="(g,index) in games" :key="index">{{g}}</h4>
            </template>
        </Category>

    </div>
</template>
<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>

总结

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

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

  3. 使用方式:

    1. 默认插槽:

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

      父组件中:
              <Category>
                  <template slot="center">
                    <div>html结构1</div>
                  </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. 理解:数据在组件的自身,数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

      2. 作用域插槽必须用<template>包裹
        <template scope="xxx"> xxx可以随意指定

      3. 具体编码:

        父组件中:
                <Category>
                    <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>
        

Vuex

1.概念

在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

Github 地址: https://github.com/vuejs/vuex

2.何时使用?

多个组件需要共享数据时

  1. 多个组件依赖于同一状态
  2. 来自不同组件的行为需要变更同一状态

全局事件总线方式

Vuex方式


原理图

原理讲解:

3.求和案例

3.1Vue实现

3.2Vuex实现

3.2.1搭建vuex环境
  1. vue2: npm i vuex@3

    vue3: npm i vuex@4

  2. Vue.use(Vuex)

  3. store

  4. vc==>store 让所有组件可看见store

state
  1. vuex 管理的状态对象
  2. 它应该是唯一的
  3. 示例代码:const state = {xxx:initvalue}
actions
  1. 值为一个对象,包含多个响应用户动作的回调函数

  2. 通过 commit( )来触发 mutation 中函数的调用, 间接更新 state

  3. 如何触发 actions 中的回调?

  4. 在组件中使用: $store.dispatch('对应的 action 回调名')触发

  5. 可以包含异步代码(定时器, ajax 等等)

  6. 示例代码:

    jiaOdd(context,value){
            console.log('actions中的jiaOdd被调用了')
            if(context.state.sum % 2){
                context.commit('JIA',value)
            }
        },
    
mutations
  1. 值是一个对象,包含多个直接更新 state 的方法

  2. 谁能调用 mutations 中的方法?如何调用?

    1. 在 action 中使用:commit('对应的 mutations 方法名') 触发
  3. mutations 中方法的特点:不能写异步代码、只能单纯的操作 state

  4. 示例代码:

    const mutations = {
        //执行加
        JIA(state,value){
            // console.log('mutations中的JIA被调用了',state,value)
            state.sum += value
        }
    }
    
步骤
  1. 创建文件:src/store/index.js

    //引入Vue核心库
    import Vue from 'vue'
    //引入Vuex
    import Vuex from 'vuex'
    //应用Vuex插件
    Vue.use(Vuex)
    
    //准备actions对象——响应组件中用户的动作
    const actions = {}
    //准备mutations对象——修改state中的数据
    const mutations = {}
    //准备state对象——保存具体的数据
    const state = {}
    
    //创建并暴露store
    export default new Vuex.Store({
        actions,
        mutations,
        state
    })
    
  2. main.js中创建vm时传入store配置项

    ......
    //引入store
    import store from './store'
    ......
    
    //创建vm
    //让所有组件可看见store
    new Vue({
        el:'#app',
        render: h => h(App),
        store
    })
    
3.2.2基本使用
  1. 初始化数据、配置actions、配置mutations,操作文件store.js

    //引入Vue核心库
    import Vue from 'vue'
    //引入Vuex
    import Vuex from 'vuex'
    //引用Vuex
    Vue.use(Vuex)
    
    const actions = {
        //响应组件中加的动作
        jia(context,value){
            // console.log('actions中的jia被调用了',miniStore,value)
            context.commit('JIA',value)
        },
    }
    
    const mutations = {
        //执行加
        JIA(state,value){
            // console.log('mutations中的JIA被调用了',state,value)
            state.sum += value
        }
    }
    
    //初始化数据
    const state = {
       sum:0
    }
    
    //创建并暴露store
    export default new Vuex.Store({
        actions,
        mutations,
        state,
    })
    
  2. 组件中读取vuex中的数据:$store.state.sum

  3. 组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据) 或直接执行操作函数 $store.commit('mutations中的方法名',数据)

    备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit

3.3 getters的使用

  1. 概念:当state中的数据需要经过加工后再使用时,可以使用getters加工。

  2. store.js中追加getters配置

    ......
    
    const getters = {
        bigSum(state){
            return state.sum * 10
        }
    }
    
    //创建并暴露store
    export default new Vuex.Store({
        ......
        getters
    })
    
  3. 组件中读取数据:$store.getters.bigSum

3.4 四个map方法的使用

import {mapState,mapGetters} from 'vuex'

  1. mapState方法: 用于帮助我们映射state中的数据为计算属性

    computed: {
        //借助mapState生成计算属性:sum、school、subject(对象写法)
         ...mapState({sum:'sum',school:'school',subject:'subject'}),
    
        //借助mapState生成计算属性:sum、school、subject(数组写法)
        ...mapState(['sum','school','subject']),
    },
    
  2. mapGetters方法: 用于帮助我们映射getters中的数据为计算属性

    computed: {
        //借助mapGetters生成计算属性:bigSum(对象写法)
        ...mapGetters({bigSum:'bigSum'}),
    
        //借助mapGetters生成计算属性:bigSum(数组写法)
        ...mapGetters(['bigSum'])
    },
    
  3. mapActions方法: 用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数

    methods:{
        //靠mapActions生成:incrementOdd、incrementWait(对象形式)
        ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
        //靠mapActions生成:incrementOdd、incrementWait(数组形式)
        ...mapActions(['jiaOdd','jiaWait'])
    }
    
  4. mapMutations方法: 用于帮助我们生成与mutations对话的方法,即:包含$store.commit(xxx)的函数

    methods:{
        //靠mapActions生成:increment、decrement(对象形式)
        ...mapMutations({increment:'JIA',decrement:'JIAN'}),
    
        //靠mapMutations生成:JIA、JIAN(对象形式)
        ...mapMutations(['JIA','JIAN']),
    }
    

备注:mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

4.modules模块化+命名空间

  1. 目的:让代码更好维护,让多种数据分类更加明确。

  2. 修改store.js

    const countAbout = {
      namespaced:true,//开启命名空间
      state:{x:1},
      mutations: { ... },
      actions: { ... },
      getters: {
        bigSum(state){
           return state.sum * 10
        }
      }
    }
    
    const personAbout = {
      namespaced:true,//开启命名空间
      state:{ ... },
      mutations: { ... },
      actions: { ... }
    }
    
    const store = new Vuex.Store({
      modules: {
        countAbout,
        personAbout
      }
    })
    
  3. 开启命名空间后,组件中读取state数据:

    //方式一:自己直接读取
    this.$store.state.personAbout.list
    //方式二:借助mapState读取:
    ...mapState('countAbout',['sum','school','subject']),
    
  4. 开启命名空间后,组件中读取getters数据:

    //方式一:自己直接读取
    this.$store.getters['personAbout/firstPersonName']
    //方式二:借助mapGetters读取:
    ...mapGetters('countAbout',['bigSum'])
    
  5. 开启命名空间后,组件中调用dispatch

    //方式一:自己直接dispatch
    this.$store.dispatch('personAbout/addPersonWang',person)
    //方式二:借助mapActions:
    ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
  6. 开启命名空间后,组件中调用commit

    //方式一:自己直接commit
    this.$store.commit('personAbout/ADD_PERSON',person)
    //方式二:借助mapMutations:
    ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
    

路由

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

  2. 前端路由:key是路径,value是组件。

  3. 什么是路由?

    1. 一个路由就是一组映射关系(key - value)
    2. key 为路径, value 可能是 function 或 component
  4. 路由分类

    1. 后端路由:

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

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

    1. 定义路由组件
    2. 注册路由
    3. 使用路由

1.基本使用

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

    安装vue3-router,命令:npm i vue-router@4

  2. 应用插件:Vue.use(VueRouter)

  3. 编写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. 实现切换(active-class可配置高亮样式)

    <router-link active-class="active" to="/about">About</router-link>
    
  5. 指定展示位置

    <router-view></router-view>
    

2.几个注意点

  1. 路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹。
  2. 跳转后,原来的路由组件,默认是被销毁掉的,需要的时候再去挂载。可通过<span data-type="text">10.缓存路由组件</span> 解决
  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. 接收参数:

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

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

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

  3. 接收参数:

    $route.params.id
    $route.params.title
    

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 .......>News</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"> 
        <router-view></router-view>
    </keep-alive>
    

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

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

  2. 具体名字:

    1. activated路由组件被激活时触发。
    2. deactivated路由组件失活时触发。
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)
},

12.路由守卫

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

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

  3. 全局守卫:router/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的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。
                                // props:{a:1,b:'hello'}
    
                                //props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。
                                // props:true
    
                                //props的第三种写法,值为函数
                                props($route){
                                    return {
                                        id:$route.query.id,
                                        title:$route.query.title,
                                        a:1,
                                        b:'hello'
                                    }
                                }
    
                            }
                        ]
                    }
                ]
            }
        ]
    })
    
    //全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
    router.beforeEach((to,from,next)=>{
        console.log('前置路由守卫',to,from)
        if(to.meta.isAuth){ //判断是否需要鉴权
            if(localStorage.getItem('school')==='atguigu'){
                next()
            }else{
                alert('学校名不对,无权限查看!')
            }
        }else{
            next()
        }
    })
    
    //全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
    router.afterEach((to,from)=>{
        console.log('后置路由守卫',to,from)
        document.title = to.meta.title || '硅谷系统'
    })
    
    export default router
    
  4. 独享守卫:

    那个路由需要则写在那个路由配置中
    
    beforeEnter(to,from,next){
        console.log('beforeEnter',to,from)
        if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
            if(localStorage.getItem('school') === 'atguigu'){
                next()
            }else{
                alert('暂无权限查看')
                // next({name:'guanyu'})
            }
        }else{
            next()
        }
    }
    
  5. 组件内守卫:

    写在组件中
    
    //进入守卫:通过路由规则,进入该组件时被调用
    beforeRouteEnter (to, from, next) {
    },
    //离开守卫:通过路由规则,离开该组件时被调用
    beforeRouteLeave (to, from, next) {
    }
    

13.路由器的history模式与hash模式

路由器的两种工作模式

  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',//这里调整
    routes:[路由]
})

Vue UI 组件库

移动端常用 UI 组件库

  1. Vant https://youzan.github.io/vant
  2. Cube UI https://didi.github.io/cube-ui
  3. Mint UI http://mint-ui.github.io
  4. NUT UI https://nutui.jd.com

PC 端常用 UI 组件库

  1. Element UI https://element.eleme.cn
  2. IView UI https://www.iviewui.com

Element UI 基本使用

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'

//完整引入
//引入ElementUI组件库
// import ElementUI from 'element-ui';
//引入ElementUI全部样式
// import 'element-ui/lib/theme-chalk/index.css';

//按需引入
import { Button,Row,DatePicker } from 'element-ui';

//关闭Vue的生产提示
Vue.config.productionTip = false

//应用ElementUI
// Vue.use(ElementUI);
Vue.component('atguigu-button', Button);
Vue.component('atguigu-row', Row);
Vue.component('atguigu-date-picker', DatePicker);

//创建vm
new Vue({
    el:'#app',
    render: h => h(App),
})

相关文章

网友评论

      本文标题:02尚硅谷B站课程Vue2.0+Vue3.0笔记-VUE2进阶

      本文链接:https://www.haomeiwen.com/subject/ljxqkjtx.html