尚硅谷Vue2同步笔记(2)

编程知识 更新时间:2023-04-25 07:08:29

首先附上Vue核心+Vue组件化开发对应博客的链接:

Vue核心与组件化开发http://t.csdn/Figfv


四、使用Vue脚手架

4.1 脚手架相关

4.1.1 初始化脚手架

说明:

        1.Vue脚手架是Vue官方提供的标准化开发工具(开发平台)        

        2.最新的版本是5.x

      

CLI:Command Line Interface 命令行接口工具

具体步骤:

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

                npm install -g @vue/cli

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

                vue create xxxx

        第三步:启动项目

                npm run serve

备注:

        如果出现下载缓慢,请配置npm淘宝镜像:

        npm config set registry https://registry.npm.taobao

4.1.2 分析脚手架

 重点分析src目录:

 main.js:

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

// 创建Vue实例对象---vm
new Vue({
  // 将App组件放入容器中
  render: h => h(App),
}).$mount('#app')

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!--针对IE浏览器的一个特殊配置,含义是让IE浏览器以最高的渲染级别渲染页面-->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--开启移动端的理想视口-->
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<!--配置网页标题-->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!--当浏览器不支持js时,noscript标签中的元素就会被渲染-->
<noscript>
    <strong>抱歉,您的浏览器不支持js,下一个新的吧</strong>
</noscript>
<div id="app"></div>
</body>
</html>

运行项目:npm run serve

4.2 脚手架相关配置

4.2.1 render函数

关于不同版本的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函数去指定具体内容

原型写法:

    render:function(createElement){
        return createElement('h1','你好')
    }

其中createElement是传入的参数,同时也是一个函数

改用箭头函数的写法:

    render:h=>h(App)

4.2.2 修改Vue脚手架默认配置

Vue脚手架隐藏了所有的webpack相关的配置,若想查看具体的webpack配置,请执行:

vue inspect > output.js

修改脚手架默认配置需要进入vue.config.js文件,添加你要修改的内容

vue不会让程序员直接接触vue的核心文件,而是在整合的时候读取你所配置的vue.config.js文件

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  /*关闭语法检查*/
  lintOnSave: false,
  pages:{
    index:{
      entry:'src/min.js'
    }
  }

})

4.2.3 ref属性

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

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

3.使用方式:

        打标识:<h1 ref="xx">...</h1>或<School ref='xx'/>

        获取:this.$refs.xx

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

<script>
import School from './components/School.vue'
export default {
  name: "App",
  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)
    }
  },
  components:{
    School
  }
}
</script>

4.2.4 props配置

props优先级高于data配置项

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

(1)传递数据:

        <Demo name="xxx"/>

(2)接收数据:

        第一种方式(只接收数据):

        props:['name']

        第二种方式(限制类型):

        props:{

                name:Number

        }

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

        props:{

                name:{

                        type:String,  //类型

                        required:true,        //必要性

                        default:"老王"        //默认值

                }

        }

备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告

           若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据

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

<script>
export default {
  name: "Student",
  data(){
    return {
      msg:"我是一个尚硅谷的学生",
      myAge:this.age    //用于修改传入的age
    }
  },
  // 第一种:数组写法(简单声明接收)
  // props:['name','sex','age']
/*第二种,对象写法,接受的同时对数据进行类型限制
  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
    }
  },
  methods:{
    updateAge(){
      this.myAge++     
    } 
  }
}
</script>

<style scoped>

</style>

4.2.5 mixin混入

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

使用方式:

        第一步定义混合,例如:

        {

                data(){...},

                methods:{...},

                ......

        }

        第二步使用混合,例如:

        (1)全局混合:Vue.mixin(xxx)

        (2)局部混合:mixins:['xxx']

mixin.js

export const mixin = {
    methods:{
        showName(){
            alert(this.name)
        }
    }
}

导入混合:局部

        其他组件导入该mixin

import {mixin} from './mixin'
export default {
  name: "Student",
  mixins:[mixin]
}

导入混合:全局(在main.js里引入)

import {mixin1,mixin2} from './components/mixin'
Vue.mixin(mixin1)
Vue.mixin(mixin2)

4.2.6 插件

功能:用于增强Vue

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

定义插件:

        对象.install=function(Vue,options){

                // 1.添加全局过滤器

                Vue.filter(...)

                //2.添加全局指令

                Vue.directive(...)

                //3.配置全局混入(混合)

                Vue.mixin(...)

                //4.添加实例方法

                Vue.prototype.$myMethod=function(){...}

                Vue.prototype.$myProperty=xxx

        }

使用插件:Vue.use(插件名)

plugins.js

export default {
    install(Vue){
        Vue.filter('mySlice',function(value){
            return value.slice(0,4)
        })

        Vue.directive('fbind',{
            bind(element,binding){
                element.value=binding.value
            },
            inserted(element,binding){
                element.focus()
            },
            update(element,binding){
                element.focus=binding.value
            }
        })

        Vue.mixin({
            methods:{
                showName(){
                    alert(this.name)
                }
            }
        })

        // 给Vue原型上添加一个方法(vm和vc都能用了)
        Vue.prototype.hello=()=>{alert('你好啊')}

    }
}

main.js

import plugins from './plugins'
//应用插件
Vue.use(plugins)

4.2.7 scoped样式

lang,指定编写样式的语言,如果是less需要安装less-loader

scoped:限定样式只为该组件服务,让样式在局部生效,防止冲突

<style lang="less" scoped>
.demo{
  background-color: blueviolet;
  .stuName{
    background-color: indianred;
  }
}

</style>

4.3 Todo-list案例

组件化编程流程(通用):

1.实现静态组件:抽取组件,使用组件实现静态页面效果(组件要按照功能点来拆分,命名不要与html元素冲突)

2.实现动态组件:考虑好数据的存放位置,数据是一个组件,还是一些组件在用:

        (1)一个组件再用:放在组件自身即可

        (2)一些组件在用:放在它们共同的父组件上

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

props适用于:

(1)父组件===>子组件 通信

(2)子组件===>父组件 通信(要求父先给子一个函数)(状态提升)

使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的

props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做


注:源码已上传至《我的资源》,欢迎大家下载学习交流~


4.4 浏览器本地存储

webStorage:

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

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

        3.相关API:

                1.xxxStorage.setItem('key','value');

                该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值

                2.xxxStorage.getItem('key');

                该方法接收一个键名作为参数,返回键名对应的值

                3.xxxStorage.removeItem('key');

                该方法接收一个键名作为参数,并把该键值对从存储中删除

                4.xxxStorage.clear()

                该方法会清空存储中的所有数据

        4.备注:

                1.sessionSotrage存储的内容会随着浏览器窗口的关闭而消失

                2.localStorage存储的内容,需要手动清除才会消失

                3.xxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null

                4.JSON.parse(null)的结果依然是null

localStorage:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>localStorage</title>
</head>
<body>
<h2>localStorage</h2>
<button onclick="saveData()">点我保存一个数据</button>
<br>
<button onclick="readData()">点我读取一个数据</button>
<br>
<button onclick="deleteData()">点我删除一个数据</button>
<br>
<button onclick="deleteAllData()">点我清除所有数据</button>
<script>
    let p={name:'张三',age:34}
    function saveData(){
        localStorage.setItem('person',JSON.stringify(p))
        localStorage.setItem('msg','hello')
    }
    function readData(){
        let person=localStorage.getItem('person')
        console.log(JSON.parse(person))
    }

    function deleteData(){
        localStorage.removeItem('msg')
    }
    function deleteAllData(){
        localStorage.clear()
    }
</script>

</body>
</html>

sessionStorage:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>sessionStorage</title>
</head>
<body>
<h2>sessionStorage</h2>
<button onclick="saveData()">点我保存一个数据</button>
<br>
<button onclick="readData()">点我读取一个数据</button>
<br>
<button onclick="deleteData()">点我删除一个数据</button>
<br>
<button onclick="deleteAllData()">点我清除所有数据</button>
<script>
  let p={name:'张三',age:34}
  function saveData(){
    sessionStorage.setItem('person',JSON.stringify(p))
    sessionStorage.setItem('msg','hello')
  }
  function readData(){
    let person=sessionStorage.getItem('person')
    console.log(JSON.parse(person))
  }

  function deleteData(){
    sessionStorage.removeItem('msg')
  }
  function deleteAllData(){
    sessionStorage.clear()
  }
</script>
</body>

4.4.1 TodoList---本地存储

①添加监视


  watch:{
    todos:{
      deep:true,
      handler(value){
        localStorage.setItem('todos',JSON.stringify(value))
      }
    }
  }

②修改data

  data(){
    return {
      todos:JSON.parse(localStorage.getItem('todos')) || []
    }

4.5 组件的自定义事件

4.5.1 绑定

自定义事件方式一:标签中绑定事件

App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <h1>{{msg}}</h1>
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传数据-->
    <School :getSchoolName="getSchoolName"/>
    <hr>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据-->
    <Student v-on:atguigu="getStudentName"/>
  </div>
</template>

<script>
import School from './components/School.vue'
import Student from './components/Student.vue'
export default {
  name: 'App',
  data(){
    return {
      msg:'你好啊'
    }
  },
  components: {
    School,
    Student
  },
  methods:{
    getSchoolName(name){
      alert('APP收到了学校名:'+name)
    },
    getStudentName(name){
      alert('APP收到了学生名:'+name)
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Student.vue

<template>
<div class="student">
  <h2>学生姓名:{{name}}</h2>
  <h2>学生性别:{{sex}}</h2>
  <button @click="sendStudentName">把学生名给APP</button>
</div>
</template>

<script>
export default {
  name: "Student",
  data(){
    return {
      name:'王五',
      sex:'女'
    }
  },
  methods:{
    sendStudentName(){
      this.$emit('atguigu',this.name)
    }
  }
}
</script>

<style scoped>
.student{
  background-color: pink;
}
</style>

自定义事件方式二:方法中绑定事件

App.vue

    <Student ref="student"/>
  mounted(){
    this.$refs.student.$on('atguigu',this.getStudentName)
  }

4.5.2 解绑

解绑一个自定义事件:

    unbind(){
      this.$off('atguigu')
    }

解绑多个自定义事件:

      this.$off(['atguigu','m1'])

解绑所有的自定义事件:

      this.$off()

4.5.3 总结

1.一种组件间通信的方式,适用于 子组件==>父组件

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

3.绑定自定义事件:

        1.第一种方式,在父组件中:<Demo @atguigu="test"/>或<Demo v-on:atguigu="test"/>

        2.第二种方式,在父组件中:

<Demo ref="demo"/>
......
mounted(){
    this.$refs.xxx.$on('atguigu',this.test)
}

        3.若想让自定义组件只触发一次,可以用once修饰符,或者$once方法

4.触发自定义组件:this.$emit('atguigu',数据)

5.解绑自定义事件:this.$off('atguigu')

6.组件上也可以绑定原生DOM事件,需要使用native修饰符

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

4.6 全局事件总线

4.6.1 全局事件总线1

全局事件总线:任意组件间通信

在main.js中挂载全局事件总线

new Vue({
  render: h => h(App),
  beforeCreate(){
    this.prototype.$bus=this
  }
}).$mount('#app')

4.6.2 全局事件总线2

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

2.安装全局事件总线:

new Vue({
  render: h => h(App),
  beforeCreate(){
    this.prototype.$bus=this // 安装全局事件总线,$bus就是当前应用的vm
  }
}).$mount('#app')

3.使用事件总线:

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

methods(){
    demo(data){......}
}
......
mounted(){
    this.$bus.$on('xxx',this.demo)
}

        2.提供数据:this.$bus.$emit('xxx',数据)

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

4.7 消息订阅与发布

报纸订阅与发布:

        1.订阅报纸:住址

        2.邮递员送报纸:报纸

消息订阅与发布:

        1.订阅消息:消息名

        2.发布消息:消息内容

下载pubsub-js

 npm i pubsub-js

总结:

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

2.使用步骤:

        1.安装pubsub:npm i pubsub-js

        2.引入:import pubsub from 'pubsub'

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

        methods(){

                demo(data){......}

        }

        ......

        mounted(){

                this.pid=pubsub.subscribe('xxx',this.demo) //订阅消息

        }

        4.提供数据:pubsub.publish('xxx',数据)

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

4.8 $nextTick

        1.语法:this.$nextTick(回调函数)

        2.作用:在下一次DOM更新结束后执行其指定的回调

        3.什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,在$nextTick所指定的回调函数中执行

      this.$nextTick(()=>{
        this.$refs.inputTitle.focus()
      })

4.9 过渡与动画

4.9.1 动画效果

<template>
<div>
  <button @click="isShow=!isShow">显示 / 影藏</button>
  <transition name="hello" appear>
    <h1 v-show="isShow">你好啊!</h1>
  </transition>
</div>
</template>

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

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

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

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

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

4.9.2 过渡效果

<template>
  <div>
    <button @click="isShow=!isShow">显示 / 影藏</button>
    <transition name="hello" appear>
      <h1 v-show="isShow">你好啊!</h1>
    </transition>
  </div>
</template>

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

<style scoped>
h1{
  background-color: darkseagreen;
}
.hello-enter,
.hello-leave-to{
  transform:translateX(-100%)
}
.hello-enter-to,
.hello-leave{
  transform:translateX(0)
}
.hello-enter-active,
.hello-leave-active{
  transition:1s;
}
</style>

4.9.3 多个元素过渡

<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: "Animation",
  data(){
    return {
      isShow:true
    }
  }
}
</script>

<style scoped>
h1{
  background-color: darkseagreen;
}
.hello-enter,
.hello-leave-to{
  transform:translateX(-100%)
}
.hello-enter-to,
.hello-leave{
  transform:translateX(0)
}
.hello-enter-active,
.hello-leave-active{
  transition:1s;
}
</style>

4.9.4 总结过渡与动画

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

2.图示:

3.写法:

        1.准备好样式:

                元素进入的样式:

                        v-enter:进入的起点

                        v-enter-active:进入过程中

                        v-enter-to:进入的终点

                元素离开的样式:

                        v-leave:离开的起点

                        v-leave-active:离开过程中

                        v-leave-to:离开的终点

        2.使用<transition>包裹要过渡的元素,并配置name属性:

<transition name="hello">
    <h1 v-show=isShow>你好啊!</h1>
</transition>

        3.备注:若有多个元素需要过渡,则需要使用<transition-group>,且为每个元素指定不同的key值

4.10 配置代理

4.10.1 配置代理---方式一

在vue.config.js文件中配置如下代码即可解决跨域问题“:

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

注意,此时发送ajax请求应为8080端口:

      axios.get('http://localhost:8080/students').then(
          response=>{
            console.log('请求成功了',response.data)
          },
          error=>{
            console.log('请求失败了',error)
          }

      )

优点:配质检单,请求资源时直接发给前端(8080)即可

不完美之处:

        ①只能配置一个代理

        ②不能智能的控制是否走代理

工作方式:若按照上述配置代理,当请求了前端不存在的资源时,该请求会转发给服务器(优先匹配前端资源)

4.10.2 配置代理---方式二

  devServer:{
    proxy:{
      '/atguigu':{  //匹配所有以'/atguigu'开头的请求路径
        target:'http://localhost:5000', //代理目标的基础路径
        pathRewrite:{'^/atguigu':''},
        ws:true,//用于支持websocket
        changeOrigin:true
      },
     '/api2':{
         target:'http://localhost:5001',
         changeOrigin:true,
         pathRewrite:{'^/api2':''}
     }
  }

changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000

changeOrigin设置为false时,服务期收到的请求头中的host为:localhost:8080

changeOrigin默认值为true

优点:可以配置多个代理,且可以灵活的控制请求是否走代理

缺点:配置略微繁琐,请求资源时必须加前缀

4.11 GitHub案例

说明:

        源码已上传自《我的资源》,欢迎大家下载学习和交流~

运行截图:

4.12 插槽

4.12.1 默认插槽

Category.vue

<template>
  <div class="category">
    <h3>{{title}}分类</h3>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: "Category",
  props:['games','title']

}
</script>

<style scoped lang="less">
 .category{
   background-color: darkseagreen;
   width:200px;
   height:300px;
    h3{
      padding-top:5px;
      background-color: orange;
      text-align:center;
      font-size:16px;
    }
 }

</style>

App.vue

<template>
  <div class="container">
    <Category title="美食">
      <img src="./assets/food.jpg" alt="">
    </Category>
    <Category :games="games" title="游戏">
      <ul>
        <li v-for="(g,index) in games" :key="index">{{g}}</li>
      </ul>
    </Category>
    <Category title="电影">
      <video controls src="./assets/887.mp3"></video>
    </Category>
  </div>
</template>

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

<style lang="less">
.container{
  width:800px;
  margin:20px auto;
  display:flex;
  justify-content: space-around;
  img{
    width:200px;
  }
  video{
    width:100%;
  }
}
</style>

效果:

4.12.2 具名插槽

App.vue

<template>
  <div class="container">
    <Category title="美食">
      <img slot="center" src="./assets/food.jpg" alt="">
      <a slot="bottom" href="http://www.atguigu">更多美食</a>
    </Category>
    <Category :games="games" title="游戏">
      <ul slot="center">
        <li v-for="(g,index) in games" :key="index">{{g}}</li>
      </ul>
    <div class="footer" slot="bottom">
      <a href="http://www.atguigu">单机游戏</a>
      <a href="http://www.atguigu">网络游戏</a>
    </div>
    </Category>
    <Category title="电影">
      <video slot="center" controls src="./assets/887.mp3"></video>
      <template v-slot:bottom>
        <div class="footer">
          <a slot="bottom" href="http://www.atguigu">经典</a>
          <a slot="bottom" href="http://www.atguigu">热门</a>
          <a slot="bottom" href="http://www.atguigu">推荐</a>
        </div>
        <h4>欢迎前来观影</h4>
      </template>
    </Category>
  </div>
</template>

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

<style lang="less">
.container{
  width:800px;
  margin:20px auto;
  display:flex;
  justify-content: space-around;
  img{
    width:200px;
  }
  video{
    width:100%;
  }
  .footer {
    text-align: center;
    a {
      margin-right: 10px;
    }
  }
}
</style>

Category.vue

<template>
  <div class="category">
    <h3>{{title}}分类</h3>
    <slot name="center"></slot>
    <slot name="bottom"></slot>
  </div>
</template>

<script>
export default {
  name: "Category",
  props:['games','title']

}
</script>

<style scoped lang="less">
 .category{
   background-color: darkseagreen;
   width:200px;
   height:300px;
    h3{
      padding-top:5px;
      background-color: orange;
      text-align:center;
      font-size:16px;
    }
 }

</style>

4.13.3 作用域插槽

App.vue

<template>
  <div class="container">
    <Category title="美食">
      <template v-slot="scope">
        <ul>
          <li v-for="(food,index) in scope.listData.foods" :key="index">{{food}}</li>
        </ul>
      </template>
    </Category>
    <Category title="游戏">
      <template v-slot="scope">
        <ol>
          <li v-for="(game,index) in scope.listData.games" :key="index">{{game}}</li>
        </ol>
      </template>
    </Category>
    <Category title="电影">
      <template v-slot="scope">
        <ol>
          <li v-for="(film,index) in scope.films" :key="index">{{film}}</li>
        </ol>
      </template>
    </Category>
  </div>
</template>

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

}
</script>

<style lang="less">
.container{
  width:800px;
  margin:20px auto;
  display:flex;
  justify-content: space-around;
}
</style>

Category.vue

<template>
  <div class="category">
    <h3>{{title}}分类</h3>
    <slot :listData="listData"></slot>
  </div>
</template>

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

}
</script>

<style scoped lang="less">
 .category{
   background-color: darkseagreen;
   width:200px;
   height:300px;
    h3{
      padding-top:5px;
      background-color: orange;
      text-align:center;
      font-size:16px;
    }
 }

</style>

4.13.4 插槽总结

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

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

3.使用方式:

        1.默认插槽

//父组件中:
<Category>
    <div>html结构1</div>
</Category>

//子组件中:
<template>
    <div>
        <slot>插槽默认内容</slot>
    </div>
</template>

        2.具名插槽

//父组件中:
<Category>
    <tempate v-slot:center>
        <div>html结构1</div>
    </template>
    <template v-slot:footer>
        <div>html结构2</div>
    </template>
</Category>


//子组件中
<template>
    <slot name="center">插槽默认内容</slot>
    <slot name="footer">插槽默认内容</slot>
</template>

        3.作用域插槽

        理解:数据在组件自身,但根据数据生成的结构需要组件的使用者来决定。(比如games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

        具体编码:

//父组件中:
<Category>
    <template v-slot="scope">
        <ol>
            <li v-for="(g,index) in scope.games" :key="index">{{g}}</li>
        </ol>
    </template>
</Category>

//子组件中
<template>
    <slot :games="games"></slot>
</template>
<script>
    export default{
        name:'Category',
        data(){
            return {
                games:['王者荣耀','绝地求生','蛋仔派对']
            }
        }
    }
</script>

注:作用域插槽接收子组件传递过来的数据时可以使用对象的解构赋值

五、vuex

5.1 vuex简介

vuex是什么?

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

全局事件总线实现:

 vuex实现:

什么时候使用vuex?

        ①多个组件依赖于同一状态

        ②来自不同组件的行为需要变更同一状态

5.2 求和案例---纯vue版

<template>
  <div id="app">
    <h1>当前求和为:{{sum}}</h1>
    <select name="" id="" v-model="n">
      <option :value="1">1</option>
      <option :value="2">2</option>
      <option :value="3">3</option>
    </select>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="incrementOdd">当前值为奇数再加</button>
    <button @click="incrementWait">等一等再加</button>
  </div>
</template>

<script>


export default {
  name: 'App',
  data(){
    return {
      sum:0,
      n:1
    }
  },
  methods:{
    increment(){
      this.sum+=this.n
    },
    decrement(){
      this.sum-=this.n
    },
    incrementOdd(){
      if(this.sum%2){
        this.sum+=this.n
      }
    },
    incrementWait(){
      setTimeout(()=>{
        this.sum+=this.n
      },3000)
    }
  }
}
</script>

<style>
button{
  margin:5px;
}
</style>

也可以不用v-bind修饰value,转而用number修饰v-model

    <select name="" id="" v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>

5.3 vuex工作原理图

在不需要后端接口提供数据的时候,actions略显多于,其实vuex允许你直接调用commit方法

vuex所有的方法、对象都由store维护

5.4 搭建vuex环境

vue2中,要用vuex的3版本

vue3中,要用vuex的4版本

 npm i vuex@3 

main.js

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

Vue.config.productionTip = false

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

index.js

// 该文件用于创建vuex中最为核心的store

//引入Vue
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//使用插件
Vue.use(Vuex)
// 准备actions---用于响应组件中的动作
const actions={}
//准备mutations---用于操作数据
const mutations={}
//准备state---用于存储数据
const state={}

//创建store并暴露
 export default new Vuex.Store({
    actions,mutations,state
})

搭建Vuex环境成功后效果:

5.5 求和案例---vuex版本

App.vue

<template>
  <div id="app">
    <h1>当前求和为:{{$store.state.sum}}</h1>
    <select name="" id="" v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="incrementOdd">当前值为奇数再加</button>
    <button @click="incrementWait">等一等再加</button>
  </div>
</template>

<script>


export default {
  name: 'App',
  data(){
    return {
      n:1
    }
  },
  methods:{
    increment(){
      this.$store.dispatch('add',this.n)
    },
    decrement(){
      this.$store.dispatch('dec',this.n)
    },
    incrementOdd(){
      this.$store.dispatch('incOdd',this.n)
    },
    incrementWait(){
      this.$store.dispatch('incWait',this.n)
    }
  }
}
</script>

<style>
button{
  margin:5px;
}
</style>

index.js

// 该文件用于创建vuex中最为核心的store

//引入Vue
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//使用插件
Vue.use(Vuex)
// 准备actions---用于响应组件中的动作
const actions={
    add(context,value){
        contextmit('ADD',value)
    },
    dec(context,value){
        contextmit('DEC',value)
    },
    incOdd(context,value){
        if(context.state.sum%2){
            contextmit('INCODD',value)
        }
    },
    incWait(context,value){
        setTimeout(()=>{
            contextmit('INCWAIT',value)
        },3000)
    }
}
//准备mutations---用于操作数据
const mutations={
    ADD(state,value){
        state.sum+=value
    },
    DEC(state,value){
        state.sum-=value
    },
    INCODD(state,value){
        state.sum+=value
    },
    INCWAIT(state,value){
        state.sum+=value
    }
}
//准备state---用于存储数据
const state={
    sum:0
}

//创建store并暴露
 export default new Vuex.Store({
    actions,mutations,state
})

优化:

App.vue

    increment(){
      this.$storemit('ADD',this.n)
    },
    decrement(){
      this.$storemit('DEC',this.n)
    }

总结:

组件中读取vuex中的数据:$store.state.sum

组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)或$storemit('mutations中的方法名',数据)

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

        不能在actions里编写commit的方法,即使可以通过context.state拿到要修改的数据,因为没有mutations,开发者工具会失效

5.6 getters配置项

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

2.在index.js中追加getters配置

// 准备getters---用于将state中的数据进行加工
const getters={
    bigSum(state){
        return state.sum*10
    }
}

//创建store并暴露
 export default new Vuex.Store({
    actions,mutations,state,getters
})

3.组件中读取数据:$store.getters.bigSum

    <h3>放大十倍为:{{$store.getters.bigSum}}</h3>

5.7 mapState和mapGetters

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

2.mapGetters方法:用于帮助我们映射getters中的数据为计算属性

  computed:{
    // 借助mapState生成计算属性,从state中读取数据(对象写法)
    //  ...mapState({sum:'sum',school:'school',subject:'subject'})

    // 数组写法
    ...mapState(['sum','school','subject']),

    ...mapGetters(['bigSum'])

  }

5.8 mapActions和mapMutations

mapMutations方法:用于帮助我们生成与mutations对话的方法,即:包含$storemit(xxx)的函数

    //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations
    ...mapMutations({increment:'ADD',decrement:'DEC'})
    //数组写法要求App.vue和index.js的方法名一致
    ...mapMutations(['ADD','DEC'])

mapActions方法:用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数

    //对象写法   
 ...mapActions({incrementOdd:'incOdd',incrementWait:'incWait'}),
    //数组写法
    ...mapActions(['incOdd','incWait'])

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

5.9 多组件共享数据

App.vue

<template>
<div>
  <Count/>
  <hr>
  <Person/>
</div>
</template>

<script>
import Count from './components/Count.vue'
import Person from './components/Person.vue'
export default {
  name: 'App',
  components:{
    Count,Person
  }

}
</script>

<style>
button{
  margin:5px;
}
</style>

Person.vue

<template>
<div>
  <h1>人员列表</h1>
  <h3>Count组件求和为:{{sum}}</h3>
  <input type="text" placeholder="请输入名字" v-model="name">
  <button @click="add">添加</button>
  <ul>
    <li v-for="p in personList" :key="p.id">{{p.name}}</li>
  </ul>
</div>
</template>

<script>
import {mapState} from 'vuex'
import {nanoid} from 'nanoid'
export default {
  name: "Person",
  data(){
    return {
      name:''
    }
  },
  computed:{
    ...mapState(['personList','sum'])
  },
  methods:{
    add(){
      const personObj={id:nanoid(),name:this.name}
      this.name=''
      this.$storemit('ADD_PERSON',personObj)
    }
  }
}
</script>

<style scoped>

</style>

Count.vue

<template>
  <div id="app">
    <h1>当前求和为:{{$store.state.sum}}</h1>
    <h3>放大十倍为:{{$store.getters.bigSum}}</h3>
    <h3>我在{{school}}学习,学科是:{{subject}}</h3>
    <h3>Person组件的总人数为:{{personList.length}}</h3>
    <select name="" id="" v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(n)">+</button>
    <button @click="decrement(n)">-</button>
    <button @click="incrementOdd(n)">当前值为奇数再加</button>
    <button @click="incrementWait(n)">等一等再加</button>
  </div>
</template>

<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'

export default {
  name: 'Count',
  data(){
    return {
      n:1
    }
  },
  methods:{
    ...mapMutations({increment:'ADD',decrement:'DEC'}),
    ...mapActions({incrementOdd:'incOdd',incrementWait:'incWait'})
  },
  computed:{
    ...mapState(['sum','school','subject','personList']),
    ...mapGetters(['bigSum'])
  }
}
</script>

<style>
button{
  margin:5px;
}
</style>

index.js

// 该文件用于创建vuex中最为核心的store

//引入Vue
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
//使用插件
Vue.use(Vuex)
// 准备actions---用于响应组件中的动作
const actions={
    incOdd(context,value){
        if(context.state.sum%2){
            contextmit('INCODD',value)
        }
    },
    incWait(context,value){
        setTimeout(()=>{
            contextmit('INCWAIT',value)
        },3000)
    }
}
//准备mutations---用于操作数据
const mutations={
    ADD(state,value){
        state.sum+=value
    },
    DEC(state,value){
        state.sum-=value
    },
    INCODD(state,value){
        state.sum+=value
    },
    INCWAIT(state,value){
        state.sum+=value
    },
    ADD_PERSON(state,value){
        state.personList.unshift(value)
    }
}
//准备state---用于存储数据
const state={
    sum:0,
    school:'尚硅谷',
    subject:'前端',
    personList:[
        {idd:'001',name:'张三'}
    ]
}
// 准备getters---用于将state中的数据进行加工
const getters={
    bigSum(state){
        return state.sum*10
    }
}

//创建store并暴露
 export default new Vuex.Store({
    actions,mutations,state,getters
})

运行截图:

5.10 vuex模块化+namespace

笔记:

 

实战:

index.js

// 该文件用于创建vuex中最为核心的store

//引入Vue
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
import axios from 'axios'
import {nanoid} from 'nanoid'
//使用插件
Vue.use(Vuex)

//求和功能相关的配置
const countOptions={
    namespaced:true,
    actions:{
        incOdd(context,value){
            if(context.state.sum%2){
                contextmit('INCODD',value)
            }
        },
        incWait(context,value){
            setTimeout(()=>{
                contextmit('INCWAIT',value)
            },3000)
        }
    },
    mutations:{
        ADD(state,value){
            state.sum+=value
        },
        DEC(state,value){
            state.sum-=value
        },
        INCODD(state,value){
            state.sum+=value
        },
        INCWAIT(state,value){
            state.sum+=value
        }
    },
    state:{
        sum:0,
        school:'尚硅谷',
        subject:'前端',
    },
    getters:{
        bigSum(state){
            return state.sum*10
        }
    }
}

const personOptions={
    namespaced:true,
    actions:{
        addPersonWang(context,value){
            if(value.name.indexOf('王')===0){
                contextmit('ADD_PERSON',value)
            }
        },
        addPersonServer(context){
            axios.get('https://api.uixsj/hitokoto/get?type=social').then(
                response=>{
                    contextmit('ADD_PERSON',{id:nanoid(),name:response.data})
                },
                error=>{
                    alert(error.message)
                }
            )
        }
    },
    mutations:{
        ADD_PERSON(state,value){
            state.personList.unshift(value)
        }
    },
    state:{
        personList:[
            {idd:'001',name:'张三'}
        ]
    },
    getters:{
        firstPersonName(state){
            return state.personList[0].name
        }
    }
}

//创建store并暴露
 export default new Vuex.Store({
    modules:{
        countOptions,personOptions
    }
})

App.vue

<template>
<div>
  <Count/>
  <hr>
  <Person/>
</div>
</template>

<script>
import Count from './components/Count.vue'
import Person from './components/Person.vue'
export default {
  name: 'App',
  components:{
    Count,Person
  }

}
</script>

<style>
button{
  margin:5px;
}
</style>

Count.vue

<template>
  <div id="app">
    <h1>当前求和为:{{sum}}</h1>
    <h3>放大十倍为:{{bigSum}}</h3>
    <h3>我在{{school}}学习,学科是:{{subject}}</h3>
    <h3>Person组件的总人数为:{{personList.length}}</h3>
    <select name="" id="" v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(n)">+</button>
    <button @click="decrement(n)">-</button>
    <button @click="incrementOdd(n)">当前值为奇数再加</button>
    <button @click="incrementWait(n)">等一等再加</button>
  </div>
</template>

<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
import count from "./Count.vue";

export default {
  name: 'Count',
  data(){
    return {
      n:1
    }
  },
  methods:{
    ...mapMutations('countOptions',{increment:'ADD',decrement:'DEC'}),
    ...mapActions('countOptions',{incrementOdd:'incOdd',incrementWait:'incWait'})
  },
  computed:{
    ...mapState('countOptions',['sum','school','subject']),
    ...mapState('personOptions',['personList']),
    ...mapGetters('countOptions',['bigSum'])
  }
}
</script>

<style>
button{
  margin:5px;
}
</style>

Person.vue

<template>
<div>
  <h1>人员列表</h1>
  <h3>Count组件求和为:{{sum}}</h3>
  <input type="text" placeholder="请输入名字" v-model="name">
  <button @click="add">添加</button>
  <button @click="addWang">添加一个姓王的人</button>
  <button @click="addPersonFromServer">添加一个人,名字随机</button>
  <h3>第一个人的名字为:{{firstName}}</h3>
  <ul>
    <li v-for="p in personList" :key="p.id">{{p.name}}</li>
  </ul>
</div>
</template>

<script>
import {mapState} from 'vuex'
import {nanoid} from 'nanoid'
export default {
  name: "Person",
  data(){
    return {
      name:''
    }
  },
  computed:{
    sum(){
      return this.$store.state.countOptions.sum
    },
    personList(){
      return this.$store.state.personOptions.personList
    },
    firstName(){
      return this.$store.getters['personOptions/firstPersonName']
    }
  },
  methods:{
    add(){
      const personObj={id:nanoid(),name:this.name}
      this.name=''
      this.$storemit('personOptions/ADD_PERSON',personObj)
    },
    addWang(){
      const personObj={id:nanoid(),name:this.name}
      this.name=''
      this.$store.dispatch('personOptions/addPersonWang',personObj)
    },
    addPersonFromServer(){
      this.$store.dispatch('personOptions/addPersonServer')
    }
  }
}
</script>

<style scoped>

</style>

效果图:

六、路由

6.1 路由的简介

1.路由就是一组key-value的对应关系

2.多个路由,需要经过路由器的管理

vue中的路由是为了实现SPA应用

 vue中的路由规则

6.1.1 相关理解

vue-router的理解:vue的一个插件库,专门用来实现SPA应用

对SPA应用的理解:

        1.单页Web应用(single page web application,SPA)

        2.整个应用只有一个完整的页面

        3.点击页面中的导航连接不会刷新页面,只会做页面的局部更新

        4.数据需要通过ajax请求获取

6.1.2 路由的理解

什么是路由?

        1.一个路由就是一组映射关系(key-value)

        2.key为路径,value可能是function或component

路由的分类

        1.后端路由:

        (1)理解:value是function,用于处理客户端提交的请求

        (2)工作过程:服务器接收到一个请求时,根据请求路径找到匹配的函数来处理请求,返回响数据

        2.前端路由:

        (1)理解:value是component,用于展示页面内容

        (2)工作过程:当浏览器的路径改变时,对应的组件就会显示

6.2 路由的基本使用

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

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

3.编写router配置项:

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入需要的组件
import About from '../components/About.vue'
import Home from '../components/Home.vue'
//  创建一个路由器
export default new VueRouter({
    routes:[
        {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home
        }
    ]
})

4.实现切换(active-class可配置高亮样式)

      <div class="list-group">
        <router-link to="/about" class="list-group-item" active-class="active">About</router-link>
        <router-link to="/home" class="list-group-item" active-class="active">Home</router-link>
      </div>

5.指定展示位置

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

6.3 几个注意点

1.路由组件通常存放在pagees文件夹,一般组件通常存放在components文件夹

2.通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载

3.每个组件都有自己的$route属性,里面存储着自己的路由信息

4.整个应用只有一个router,可以通过组件的$router属性获取到

6.4 嵌套路由

①配置好子组件:

Message.vue

<template>
  <div>
    <ul>
      <li>
        <router-link to="/home/message">message001</router-link>&nbsp;&nbsp;
      </li>
      <li>
        <router-link to="/home/message">message002</router-link>&nbsp;&nbsp;
      </li>
      <li>
        <router-link to="/home/message">message003</router-link>&nbsp;&nbsp;
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Message"
}
</script>

<style scoped>

</style>

News.vue

<template>
<ul>
  <li>news001</li>
  <li>news002</li>
  <li>news003</li>
</ul>
</template>

<script>
export default {
  name: "News"
}
</script>

<style scoped>

</style>

②配置路由

通过children关键词配置二级路由,注意二级路由配置路径时不需要添加斜线/

        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:'message',
                    component:Message
                },
                {
                    path:'news',
                    component:News
                }
            ]
        }

③在一级路由中配置二级路由

<template>
  <div>
    <h2>我是Home的内容</h2>
    <ul class="nav nav-tabs">
      <li>
        <router-link to="/home/news" active-class="active" class="list-group-item">News</router-link>
      </li>
      <li>
        <router-link to="/home/message" active-class="active" class="list-group-item">Message</router-link>
      </li>
    </ul>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Home"
}
</script>

6.5 路由的query参数

1.传递参数:

<!--        跳转路由并携带query参数,to的字符串写法-->
        <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp;
<!--      跳转路由并携带query参数,to的对象写法-->
        <router-link :to="{
          path:'/home/message/detail',
          query:{
            id:m.id,
            title:m.title
          }
        }">
          {{m.title}}
        </router-link>

2.接收参数

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

6.6 命名路由

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

2.如何使用

 ①给路由命名

export default new VueRouter({
    routes:[
        {
            name:'about',
            path:'/about',
            component:About
        },
        {
            name:'home',
            path:'/home',
            component:Home,
            children:[
                {
                    name:'message',
                    path:'message',
                    component:Message,
                    children:[
                        {
                            name:'detail',
                            path:'detail',
                            component:Detail
                        }
                    ]
                },
                {
                    name:'news',
                    path:'news',
                    component:News
                }
            ]
        }
    ]
})

②简化跳转:

简化前,需要写完整的路径:

        <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp;

简化后,直接通过名字跳转:

        <router-link :to="{
          name:'detail',
          query:{
            id:m.id,
            title:m.title
          }
        }">
          {{m.title}}
        </router-link>

备注:即使配置了name,path在路由配置中也是必须的参数,如果没有,将报以下错误

6.7 路由的params参数

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

        {
            name:'home',
            path:'/home',
            component:Home,
            children:[
                {
                    name:'message',
                    path:'message',
                    component:Message,
                    children:[
                        {
                            name:'detail',
                            path:'detail/:id/:title',
                            component:Detail
                        }
                    ]
                }
            ]
        }

2.传递参数

<!--        跳转路由并携带params参数,to的字符串写法-->
        <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp;
<!--      跳转路由并携带params参数,to的对象写法-->
        <router-link :to="{
          name:'detail',
          params:{
            id:m.id,
            title:m.title
          }
        }">
          {{m.title}}
        </router-link>

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

3.接收参数

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

6.8 路由的props配置

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

路由配置:



        {
            name:'detail',
            path:'detail/:id/:title',
            component:Detail,
            //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
                }
            }
        }

接收props:

  props:['id','title']

备注:

props值为函数时,可以使用对象的连续解构赋值,但可读性会差一些

//props的第三种写法,值为函数
props({query:{id,title}}){
    return {
        id,title
    }
}

6.9 router-link的replace属性

1.作用:控制路由跳转时操作浏览器历史记录的模式

2.浏览器的历史记录有两种写入方式:分别为push和replace,push是追加历史记录,replace是替换当前记录。路由跳转的时候默认为push

3.如何开启replace模式:

        <router-link to="/about" replace>About</router-link>

4.开启router-link的replace模式的效果:

6.10  编程式路由导航

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

2.具体编码

    pushShow(m){
      this.$router.push({
        name:'detail',
        query:{
          id:m.id,
          title:m.title
        }
      })
    },
    replaceShow(m){
      this.$router.replace({
        name:'detail',
        query:{
          id:m.id,
          title:m.title
        }
      })
    }

3.拓展

        可以通过路由器上的back/forward/go控制路由跳转

<template>
  <div class="col-md-offset-4 col-md-8">
    <div class="page-header">
      <h2>Vue Router Demo</h2>
      <button @click="back">后退</button>
      <button @click="forward">前进</button>
      <button @click="go">go</button>
    </div>
  </div>
</template>

<script>
export default {
  name: "Banner",
  methods:{
    back(){
      this.$router.back()
    },
    forwrad(){
      this.$router.forward()
    },
    go(){
      this.$router.go(-2)
    }
  }
}
</script>

<style scoped>

</style>

6.11 缓存路由组件

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

2.具体编码:

    <keep-alive include="News">
      <router-view></router-view>
    </keep-alive>

注意:

        ①不写include,则在<router-view></router-view>中展示的组件都将被缓存

        ②include中应写组件名,组件名是在组件中用name配置的名字

        ③include中缓存多个组件名,应写为数组形式

6.12 两个新的生命周期钩子

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

2.具体名字:

        ①activated路由组件被激活时触发

        ②deactivated路由组件失活时触发

  activated(){
    this.timer=setInterval(()=>{
      this.opacity -= 0.01
      if(this.opacity<=0) this.opacity=1
    },16)
  },
  deactivated(){
    clearInterval(this.timer)
  }

6.13 路由守卫

6.13.1 全局前置

//全局前置路由守卫---初始化的时候、每次路由切换之前被调用
router.beforeEach((to,from,next)=>{
    if(to.name==='news'||to.name==='message'){
        if(localStorage.getItem('school')==='atguigu'){
            next()
        }else{
            alert('学校名不对,无权限查看')
        }
    }else{
        next()
    }
})

6.13.2 全局后置

常常配合前置守卫,用于对标题的切换

//全局前置路由守卫---初始化的时候、每次路由切换之前被调用
router.beforeEach((to,from,next)=>{
    if(to.meta.isAuth){
        if(localStorage.getItem('school')==='atguigu'){
            next()
        }else{
            alert('学校名不对,无权限查看!')
        }
    }else{
        next()
    }
})
//全局后置路由守卫---初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from)=>{
    document.title=to.meta.title||'尚硅谷系统'
})

6.13.3 独享路由守卫

独享路由守卫只有beforeEnter,没有afterEnter


beforeEnter:(to,from,next)=>{
    if(localStorage.getItem('school')==='atguigu'){
        next()
    }else{
        alert('学校名不对,无权限查看!')
    }
}

6.13.4 组件内路由守卫

  // 通过路由规则,进入该组件时被调用
  beforeRouteEnter(to,from,next){
    if(to.meta.isAuto){
      if(localStorage.getItem('school')==='atguigu'){
        next()
      }else{
        alert('学校名不对,无权限查看')
      }
    }else{
      next()
    }
  },
  // 通过路由规则,离开该组件时被调用
  beforeRouteLeave(to,from,next){
    next()
  }

6.14 history模式和hash模式

1.对于一个url来说,什么是hash值?

        #及其后面的值就是hash值

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

3.hash模式:

        1.地址中永远带着#号,不美观

        2.若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法

        3.兼容性好

4.history模式:

        1.地址干净、美观

        2.兼容性和hash模式相比略差

        3.应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题

5.在路由配置中,默认模式为hash,可以通过 mode:"history"调整为history模式

6.项目上线,需要将.vue文件等转换为纯粹的浏览器可以识别的html、css、js等

        通过命令:npm run build

        然后将生成的dist文件交给后端即可下班

7.后端需要解决前端的history模式带来的问题

        具体的解决方案是安装:connect-history-api-fallback

npm i connect-history-api-fallback

        然后使用该中间件即可

const express=require('express')
const history=require('connect-history-api-fallback')

const app=express()

app.use(history())
app.use(express.static(__dirname+'/static'))

//后略

七、element-ui

7.1 element-ui基本使用

①下载element-ui

 npm i element-ui -S 

②引入

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

//应用ElementUI
Vue.use(ElementUI)

③直接使用(例子)

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

效果图:

7.2 element-ui按需引入

借助babel-plugin-component,我们可以只引入需要的组件,以达到减小项目体积的目的

①安装babel-plugin-component

npm install babel-plugin-component -D

②修改配置文件:babel.config.js

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset',
      ["@babel/preset-env",{"modules":false}]
  ],
  "plugins":[
      [
          "component",
        {
          "libraryName":"element-ui",
          "styleLibraryName":"theme-chalk"
        }
      ]
  ]
}

③在main.js中实现按需引入

import {Button,Row} from 'element-ui'

Vue.use(Button)
Vue.use(Row)


Vue2完结撒花❀❀~~

祝大家学业有成,前途似锦~~

更多推荐

尚硅谷Vue2同步笔记(2)

本文发布于:2023-04-19 02:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/dd004da6d888adaf77ac11a172b48b54.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:硅谷   笔记

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 86928文章数
  • 19046阅读数
  • 0评论数