admin管理员组

文章数量:1655715

一、Vue 初次上手

目录

一、Vue 初次上手

 1. Vue 概念

2.创建 Vue 实例,初始化渲染

 3.插值表达式

4.响应式特性

5.安装 Vue 开发者工具: 装插件调试 Vue 应用

二、Vue 指令 

1.内容渲染指令 v-text,v-html

 2.1 条件渲染指令 v-show , v-if

2.2 条件渲染指令 v-else, v-else-if

3.事件绑定指令  v-on

1️⃣内联语句实现

2️⃣事件处理函数

3️⃣给事件处理函数传参

4.属性绑定指令 v-bind

✍🏻图片切换案例:波仔学习之旅

5.列表渲染指令 v-for

✍🏻图书管理案例 - 书架

🌟v-for中的key

6.双向绑定指令  v-model

✍🏻综合案例-记事本

功能总结:

三、指令补充

1.指令修饰符

1️⃣按键修饰符

2️⃣v-model修饰符

3️⃣事件修饰符

2.v-bind对样式控制的增强

1️⃣操作class

✍🏻案例:京东秒杀-tab栏切换导航高亮

2️⃣操作style

3.v-model在其他表单元素的使用

四、computed计算属性

1puted 计算属性 VS methods方法

1️⃣computed 计算属性

2️⃣ methods计算属性

计算属性的优势

2.计算属性的完整写法

✍🏻综合案例-成绩案例 

五、watch侦听器(监视器)

watch侦听器完整写法

✍综合案例-购物车

代码实现: 

六、生命周期以及四个阶段

Vue生命周期钩子

1️⃣在created中发送数据

2️⃣在mounted中获取焦点

✍🏻案例-记账清单

七、工程化开发和脚手架

1.开发Vue的两种方式

2.脚手架 Vue CLI

八、项目目录介绍和运行流程 

1.项目目录介绍 

2.运行流程 

九、组件化开发 

根组件 App.vue

1.根组件介绍

 2.App.vue 文件 (单文件组件) 的三个组成部分

 3.总结

十、普通组件的注册使用-局部注册

十一、普通组件的注册使用-全局注册

📜总结

✍🏻综合案例——小兔仙购物


 1. Vue 概念

概念: Vue 是一个用于 构建用户界面 渐进式 框架 

①构建用户界面:基于数据动态渲染出用户看到的页面

 ②渐进式:循序渐进

Vue的两种使用方式:

①Vue 核心包开发

·场景: 局部 模块改造

②Vue核心包&Vue插件工程化开发

·场景: 整站 开发

③框架:一套完整的项目解决方案 

  • 优点:大大提升开发效率(提升70%)
  • 缺点: 需要理解记忆规则—>官网 
  • 框架与库的对比:
  • 库,类似工具箱,是一堆方法的集合,比如 axios、lodash、echarts等
  • 框架,是一套完整的解决方案,实现了大部分功能,我们只需要按照一定的规则去编码即可。


2.创建 Vue 实例,初始化渲染

 例如:

 

构建用户界面步骤:创建Vue实例初始化渲染

  1. 准备容器 div
  2. 引包(官网) - 开发版本 /生产版本
  3. 创建Vue 实例 new Vue()
  4. 指定配置项—>渲染数据
    1. el 指定挂载点(通过 el 配置选择器,选择器 指定 Vue 管理的是哪个盒子)
    2. data 提供页面渲染的数据


 3.插值表达式

插值表达式是一种 Vue的模板语法

1.作用: 利用表达式进行插值,渲染到页面中

表达式: 是可以被求值的代码,JS引擎会将其计算出一个结果

money + 100
money - 100
money * 10
money / 10 
price >= 100 ? '真贵':'还行'
obj.name
arr[0]
fn()
obj.fn()

 2.语法:{{ 表达式 }}

<h3>{{ title }}</h3>
<p>{{ nickname.toUpperCase() }}</p>
<p>{{ age >= 18 ? '成年' : '未成年' }}</p>
<p>{{ obj.name }}</p>

⭕注意:

1.在插值表达式中使用的数据 必须在data中进行了提供
<p>{{hobby}}</p>  //如果在data中不存在 则会报错

2.支持的是表达式,而非语句,比如:if   for ...
<p>{{if}}</p>

3.不能在标签属性中使用 {{  }} 插值 (插值表达式只能标签中间使用)
<p title="{{username}}">我是P标签</p>


4.响应式特性

 1.概念:

响应式:  数据变化,视图自动更新

如何访问 or 修改?

data中的数据,最终会被添加到实例上

  • 访问数据: "实例属性名
  • 修改数据: "实例.属性名”="值 

聚焦于数据 —>数据驱动视图
使用 Vue 开发,关注业务的核心逻辑,根据业务修改数据即可


5.安装 Vue 开发者工具: 装插件调试 Vue 应用

  1. 通过谷歌应用商店安装(国外网站)
  2. 极简插件下载(推荐) 

 下载—>开发者模式—>拖拽安装—>插件详情允许访问文件

 安装之后可以F12后看到多一个Vue的调试面板

 打开 Vue 运行的页面,调试工具中 Vue 栏,即可查看修改数据,进行调试


二、Vue 指令 

Vue 会根据不同的 [指令] ,针对标签实现不同的 [功能]

1.内容渲染指令 v-text,v-html

1.概念:指令(Directives)是 Vue 提供的带有 v- 前缀 的 特殊 标签属性

目的:提高程序员操作 DOM 的效率,解决不同业务需求。

例:

<!-- Vue 指令: v- 前缀的标签属性 -->
<div v-html="str"></div>

<!-- 普通标签属性 -->
<div class="box">···</div>
<div title="小张">···</div>

v-html:
作用:设置元素的 innerHTML
语法: V-html="表达式" 

Vue 中的指令按照不同的用途可以分为如下 6 大类:

  • 内容渲染指令(v-html、v-text)
  • 条件渲染指令(v-show、v-if、v-else、v-else-if)
  • 事件绑定指令(v-on)
  • 属性绑定指令 (v-bind)
  • 双向绑定指令(v-model)
  • 列表渲染指令(v-for)

指令是 Vue 开发中最基础、最常用、最简单的知识点。

内容渲染指令:辅助开发者渲染 DOM 元素的文本内容。常用的内容渲染指令有如下2 个:

  • 1️⃣v-text(类似innerText)

    • 使用语法:<p v-text="uname">hello</p>,意思是将 uame 值渲染到 p 标签中
    • 类似 innerText,使用该语法,会覆盖 p 标签原有内容
  • 2️⃣v-html(类似 innerHTML)

    • 使用语法:<p v-html="intro">hello</p>,意思是将 intro 值渲染到 p 标签中
    • 类似 innerHTML,使用该语法,会覆盖 p 标签原有内容
    • 类似 innerHTML,使用该语法,能够将HTML标签的样式呈现出来。

例:

 
  <div id="app">
    <h2>个人信息</h2>
	// 既然指令是vue提供的特殊的html属性,所以咱们写的时候就当成属性来用即可
    <p v-text="uname">姓名:</p> 
    <p v-html="intro">简介:</p>
  </div> 

<script>
        const app = new Vue({
            el:'#app',
            data:{
                uname:'张三',
                intro:'<h2>这是一个<strong>非常优秀</strong>的boy<h2>'
            }
        })
</script>


 2.1 条件渲染指令 v-show , v-if

1.底层原理:

  • v-show: 切换 css 的 display: none 来控制显示隐藏
  • v-if : 根据 判断条件 控制元素的 创建 和 移除(条件渲染)

2.对比:

1️⃣v-show

  1. 作用: 控制元素显示隐藏
  2. 语法: v-show = "表达式" 表达式值为 true 显示, false 隐藏
  3. 原理: 切换 display:none 控制显示隐藏
  4. 场景:频繁切换显示隐藏的场景

 2️⃣v-if

  1. 作用: 控制元素显示隐藏(条件渲染)
  2. 语法: v-if= "表达式" 表达式值 true显示, false 隐藏
  3. 原理: 基于条件判断,是否创建 或 移除元素节点
  4. 场景: 要么显示,要么隐藏,不频繁切换的场景


2.2 条件渲染指令 v-else, v-else-if

v-else 和 v-else-if

  1. 作用:辅助 v-if 进行判断渲染
  2. 语法:v-else v-else-if="表达式"
  3. 需要紧接着v-if使用
<div id="app">
    <p>性别:♂ 男</p>
    <p>性别:♀ 女</p>
    <hr>
    <p>成绩评定A:奖励电脑一台</p>
    <p>成绩评定B:奖励周末郊游</p>
    <p>成绩评定C:奖励零食礼包</p>
    <p>成绩评定D:惩罚一周不能玩手机</p>
  </div>
  
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>

    const app = new Vue({
      el: '#app',
      data: {
        gender: 2,
        score: 95
      }
    })
  </script>


3.事件绑定指令  v-on

1.作用: 注册事件 = 添加监听 +提供处理逻辑
2.语法:

  1.  v-on:事件名 ="内联语句
  2.  v-on:事件名="methods中的函数名"   简写:@事件名

  1️⃣内联语句实现

<button V-on:click="count++">按钮</button>
<div id="app">
    <button @click="count--">-</button>
    <span>{{ count }}</span>
    <button v-on:click="count++">+</button>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        count: 100
      }
    })
  </script>

2️⃣事件处理函数

<button @click="fn">-</button>

<script>
    const app = new Vue({
        el:'#app',
        data:{
            // 提供数据
            count: 100
        },
        methods:{
            // 提供处理逻辑函数
            fn () {
                console.log('提供逻辑代码')
            }
        }
    }
})
</scritp>
<div id="app">
    <button>切换显示隐藏</button>
    <h1 v-show="isShow">黑马程序员</h1>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        isShow: true,
      },
       methods:{
        fn(){
            app3.isShow = !app3.isShow
        }
       }
    })
  </script>

⭕注意:

  • 事件处理函数应该写到一个跟data同级的配置项(methods)中
  • methods 让提供的所有methods中的函数,this都指向当前实例——methods中的函数内部的this都指向Vue实例

3️⃣给事件处理函数传参

  • 如果不传递任何参数,则方法无需加小括号;methods方法中可以直接使用 e 当做事件对象

  • 如果传递了参数,则实参 $event 表示事件对象,固定用法。

<style>
    .box {
      border: 3px solid #000000;
      border-radius: 10px;
      padding: 20px;
      margin: 20px;
      width: 200px;
    }
    h3 {
      margin: 10px 0 20px 0;
    }
    p {
      margin: 20px;
    }
  </style>

 <div id="app">
    <div class="box">
      <h3>小黑自动售货机</h3>
      <button>可乐5元</button>
      <button>咖啡10元</button>
      <button>牛奶8元</button>
    </div>
    <p>银行卡余额:{{ money }}元</p>
  </div>

  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        money: 100
      }
    })
  </script>


4.属性绑定指令 v-bind

1.作用:动态设置html的标签属性 比如:src、url、title

2.语法:v-bind:属性名=“表达式”

3.注意: 简写形式:属性名="表达式"

比如,有一个图片,它的 src 属性值,是一个图片地址。这个地址在数据 data 中存储。

则可以这样设置属性值:

  • <img v-bind:src="url" />
  • <img :src="url" /> (v-bind可以省略)
 <div id="app">
    <img v-bind:src="imgUrl" v-bind:title="msg" alt="">
    <img :src="imgUrl" :title="msg" alt="">
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        imgUrl: './imgs/10-02.png',
        msg: 'hello 波仔'
      }
    })
  </script>


✍🏻图片切换案例:波仔学习之旅

核心思路分析:

  1. 数组存储图片路径 ——> [ 图片1,图片2,图片3, ...]
  2. 准备下标 index,数组[下标] ——> v-bind 设置 src 展示图片 ——> 修改下标切换图片
  3. 点击上一页下一页只需要修改下标的值即可
  4. 当展示第一张的时候,上一页按钮应该隐藏。展示最后一张的时候,下一页按钮应该隐藏
 <div id="app">
    <button v-show="index > 0">上一页</button>
    <div>
      <img :src alt="list[index]" alt="">
    </div>
    <button v-show="index < list.length -1">下一页</button>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        list: [
          './imgs/11-00.gif',
          './imgs/11-01.gif',
          './imgs/11-02.gif',
          './imgs/11-03.gif',
          './imgs/11-04.png',
          './imgs/11-05.png',
        ]
      }
    })
  </script>


5.列表渲染指令 v-for

1.作用: 基于数据循环,多次染整个元素 ——> 数组、对象、数字...

2.遍历数组语法:
v-for = "(item,index) in 数组"

  • item 每一项,index 下标
  • 省略 index: v-for = "item in 数组"
 <div id="app">
    <h3>水果店</h3>
    <ul>
        <li v-for="(item,index) in list">
            {{item}} - {{index}}
        </li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        list: ['西瓜','苹果','鸭梨','榴莲']
      }
    })
  </script>

Vue 提供了 v-for 列表渲染指令,用来辅助开发者基于一个数组来循环渲染一个列表结构。

v-for 指令需要使用 (item, index) in arr 形式的特殊语法,其中:

  • item 是数组中的每一项
  • index 是每一项的索引,不需要可以省略
  • arr 是被遍历的数组

此语法也可以遍历对象和数字

//遍历对象
<div v-for="(value, key, index) in object">{{value}}</div>
value:对象中的值
key:对象中的键
index:遍历索引从0开始

//遍历数字
<p v-for="item in 10">{{item}}</p>
item从1 开始


✍🏻图书管理案例 - 书架

需求:

1.根据左侧数据渲染出右侧列表(v-for)

2.点击删除按钮时,应该把当前行从列表中删除(获取当前行的id,利用filter进行过滤)

  1. 基本渲染 ——> v-for
  2. 删除功能
<div id="app">
    <h3>书架</h3>
    <ul>
      <li v-for = "(item,index) in booksList" :key="item.id">
        <span>{{ item.name }}</span>
        <span>{{ item.author}}</span>
        <!-- 注册点击事件 ——> 通过 id 进行删除数组中的 对应项 -->
        <button @click="del(item.id)">删除</button>
      </li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        booksList: [
          { id: 1, name: '《红楼梦》', author: '曹雪芹' },
          { id: 2, name: '《西游记》', author: '吴承恩' },
          { id: 3, name: '《水浒传》', author: '施耐庵' },
          { id: 4, name: '《三国演义》', author: '罗贯中'}
        ],
      },
     methods:{
            del(id){
              // 通过 id 进行删除数组中的 对应项 ——> filter(但filter并不会改变原数组)
              // filter: 根据条件,保留满足条件的对应项,得到一个新数组
              //🌟需要将新的数组赋值给原数组      
              this.bookList = this.bookList.filter(item => item.id == id)   
              //箭头函数使用箭头(=>)来声明函数,可以省略function关键字和花括号,
              //并且可以在只有一个参数的情况下省略参数的括号
      }
    })
  </script>


🌟v-for中的key

  • 语法: key="唯一值"
  • 作用:给列表项添加的唯一标识。便于Vue进行列表项的正确排序复用
  • 为什么要加 key :Vue 的默认行为会尝试原地修改元素(就地复用

⭕注意:

  1. key 的值只能是字符串 或 数字类型
  2. key 的值必须具有唯一性
  3. 推荐使用 id 作为 key(唯一),不推荐使用 index 作为 key(会变化,不对应)


6.双向绑定指令  v-model

1.作用: 给 表单元素 使用,双向数据绑定 ——>可以快速 获取 或 设置 表单元素内容

  • 数据变化 ——> 视图自动更新
  • 视图变化 ——> 数据自动更新

2.语法: v-model=‘变量’

<div id="app">
    账户:<input type="text"> <br><br>
    密码:<input type="password"> <br><br>
    <button>登录</button>
    <button>重置</button>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        username: '',
        password: ''
      },
    })
  </script>


✍🏻综合案例-记事本

功能需求:

  1. 列表渲染
  2. 删除功能
  3. 添加功能
  4. 底部统计 和 清空

1️⃣列表渲染以及删除功能实现代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./css/index.css" />
<title>记事本</title>
</head>
<body>

<!-- 主体区域 -->
<section id="app">
  <!-- 输入框 -->
  <header class="header">
    <h1>小黑记事本</h1>
    <input  placeholder="请输入任务" class="new-todo" />
    <button class="add">添加任务</button>
  </header>
  <!-- 列表区域 -->
  <section class="main">
    <ul class="todo-list">
      <li class="todo" v-for="(item, index) in list" :key="item.id">
        <div class="view">
          <span class="index">{{ index + 1 }}.</span> <label>{{ item.name }}</label>
          <button @click="del(item.id)" class="destroy"></button>
        </div>
      </li>
    </ul>
  </section>
  <!-- 统计和清空 -->
  <footer class="footer">
    <!-- 统计 -->
    <span class="todo-count">合 计:<strong> 2 </strong></span>
    <!-- 清空 -->
    <button class="clear-completed">
      清空任务
    </button>
  </footer>
</section>

<!-- 底部 -->
<script src="https://cdn.jsdelivr/npm/vue/dist/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      list: [
        { id: 1, name: '跑步一公里' },
        { id: 3, name: '游泳100米' },
      ]
    },
    methods: {
      del (id) {
        // console.log(id) => filter 保留所有不等于该 id 的项
        this.list = this.list.filter(item => item.id !== id)
        //记得赋值给回原数组
      }
    }
  })

</script>
</body>
</html>

2️⃣添加功能

  1. 通过 v-model 绑定 输入框 实时获取表单元素的内容
  2. 点击按钮,进行新增,往数组最前面加 unshift
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./css/index.css" />
<title>记事本</title>
</head>
<body>

<!-- 主体区域 -->
<section id="app">
  <!-- 输入框 -->
  <header class="header">
    <h1>小黑记事本</h1>
    <input v-model="todoName"  placeholder="请输入任务" class="new-todo" />
    <button @click="add" class="add">添加任务</button>
  </header>
  <!-- 列表区域 -->
  <section class="main">
    <ul class="todo-list">
      <li class="todo" v-for="(item, index) in list" :key="item.id">
        <div class="view">
          <span class="index">{{ index + 1 }}.</span> <label>{{ item.name }}</label>
          <button @click="del(item.id)" class="destroy"></button>
        </div>
      </li>
    </ul>
  </section>
  <!-- 统计和清空 -->
  <footer class="footer">
    <!-- 统计 -->
    <span class="todo-count">合 计:<strong> 2 </strong></span>
    <!-- 清空 -->
    <button class="clear-completed">
      清空任务
    </button>
  </footer>
</section>

<!-- 底部 -->
<script src="https://cdn.jsdelivr/npm/vue/dist/vue.js"></script>
<script>
  // 添加功能
  // 1. 通过 v-model 绑定 输入框 → 实时获取表单元素的内容
  // 2. 点击按钮,进行新增,往数组最前面加 unshift
  const app = new Vue({
    el: '#app',
    data: {
      todoName: '',
      list: [
        { id: 1, name: '跑步一公里' },
        { id: 3, name: '游泳100米' },
      ]
    },
    methods: {
      del (id) {
        // console.log(id) => filter 保留所有不等于该 id 的项
        this.list = this.list.filter(item => item.id !== id)
      },
      add () {
        if (this.todoName.trim() === '') { //做清空判断
          alert('请输入任务名称')
          return
        }
        this.list.unshift({
          id: +new Date(),//时间戳
          name: this.todoName
        })
        this.todoName = ''
      }
    }
  })

</script>
</body>
</html>

3️⃣删除功能实现

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="./css/index.css" />
<title>记事本</title>
</head>
<body>

<!-- 主体区域 -->
<section id="app">
  <!-- 输入框 -->
  <header class="header">
    <h1>小黑记事本</h1>
    <input v-model="todoName"  placeholder="请输入任务" class="new-todo" />
    <button @click="add" class="add">添加任务</button>
  </header>
  <!-- 列表区域 -->
  <section class="main">
    <ul class="todo-list">
      <li class="todo" v-for="(item, index) in list" :key="item.id">
        <div class="view">
          <span class="index">{{ index + 1 }}.</span> <label>{{ item.name }}</label>
          <button @click="del(item.id)" class="destroy"></button>
        </div>
      </li>
    </ul>
  </section>
  <!-- 统计和清空 → 如果没有任务了,底部隐藏掉 → v-show -->
  <footer class="footer" v-show="list.length > 0">
    <!-- 统计 -->
    <span class="todo-count">合 计:<strong> {{ list.length }} </strong></span>
    <!-- 清空 -->
    <button @click="clear" class="clear-completed">
      清空任务
    </button>
  </footer>
</section>

<!-- 底部 -->
<script src="https://cdn.jsdelivr/npm/vue/dist/vue.js"></script>
<script>
  // 添加功能
  // 1. 通过 v-model 绑定 输入框 → 实时获取表单元素的内容
  // 2. 点击按钮,进行新增,往数组最前面加 unshift
  const app = new Vue({
    el: '#app',
    data: {
      todoName: '',
      list: [
        { id: 1, name: '跑步一公里' },
        { id: 2, name: '跳绳200个' },
        { id: 3, name: '游泳100米' },
      ]
    },
    methods: {
      del (id) {
        // console.log(id) => filter 保留所有不等于该 id 的项
        this.list = this.list.filter(item => item.id !== id)
      },
      add () {
        if (this.todoName.trim() === '') {
          alert('请输入任务名称')
          return
        }
        this.list.unshift({
          id: +new Date(),
          name: this.todoName
        })
        this.todoName = ''
      },
      clear () {
        this.list = []
      }
    }
  })

</script>
</body>
</html>

功能总结:

①列表渲染:
v-for  key 的设置 {{ }} 插值表达式
②删除功能
v-on 调用传参  filter 过滤 覆盖修改原数组
③添加功能
v-model 绑定   unshift 修改原数组添加
④底部统计和清空

  • 数组 .length 累计长度
  • 覆盖数组清空列表
  • v-show 控制隐藏


接下来内容如下:

三、指令补充

1.指令修饰符

简介:

指令修饰符:通过 “.” 指明一些指令后缀 不同的后缀封装了不同的处理操作 —> 简化代码

①按键修饰符

@keyup.enter ——> 键盘回车监听


②v-model修饰符
v-model.trim  ——> 去除首尾空格
v-model.number ——> 转数字

③事件修饰符
@事件名.stop  ——> 阻止冒泡
@事件名.prevent ——> 阻止默认行为

1️⃣按键修饰符

  • @keyup.enter —> 当点击enter键的时候才触发

代码演示:

<div id="app">
    <h3>@keyup.enter  →  监听键盘回车事件</h3>
    <input  @keyup.enter = "fn" v-model="username" type="text">
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        username: ''
      },
      methods: {
        fn(e){
            //if(e.key === 'Enter'){
            //    console.log('键盘回车触发',this.username)
            //}  加了.enter 相对于 封装了以上的方法
        }
      }
    })
  </script>

2️⃣v-model修饰符

  • v-model.trim —>去除首位空格
  • v-model.number —>转数字

3️⃣事件修饰符

  • @事件名.stop —> 阻止冒泡
  • @事件名.prevent —>阻止默认行为
  • @事件名.stop.prevent —>可以连用 即阻止事件冒泡也阻止默认行为

事件冒泡:是一种在Web开发中常见的现象。在浏览器中,网页上的元素(比如按钮、文本框、链接等)可以触发各种事件(比如点击事件、鼠标移动事件等)。当一个事件被触发后,它会首先被触发该元素上的事件处理程序,然后逐级向上冒泡传递给该元素的父元素,一直传递到DOM树的根节点。这样,如果父元素也有相应的事件处理程序,它也可以响应这个事件。

<style>
    .father {
      width: 200px;
      height: 200px;
      background-color: pink;
      margin-top: 20px;
    }
    .son {
      width: 100px;
      height: 100px;
      background-color: skyblue;
    }
  </style>

 <div id="app">
    <h3>v-model修饰符 .trim .number</h3>
    姓名:<input v-model="username" type="text"><br>
    年纪:<input v-model="age" type="text"><br>

    
    <h3>@事件名.stop     →  阻止冒泡</h3>
    <div @click="fatherFn" class="father">
      <div @click="sonFn" class="son">儿子</div>
    </div>

    <h3>@事件名.prevent  →  阻止默认行为</h3>
    <a @click href="http://www.baidu">阻止默认行为</a>
  </div>

  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        username: '',
        age: '',
      },
      methods: {
        fatherFn () {
          alert('老父亲被点击了')
        },
        sonFn (e) {
          // e.stopPropagation()
          alert('儿子被点击了')
        }
      }
    })
  </script>


2.v-bind对样式控制的增强

1️⃣操作class

为了方便开发者进行样式控制, Vue 扩展了 v-bind 的语法,可以针对 class 类名 和 style 行内样式 进行控制 。

1.语法:

<div> :class = "对象/数组">这是一个div</div>

2.对象语法

当class动态绑定的是对象时,键就是类名,值就是布尔值,如果值是true,就有这个类,否则没有这个类

<div class="box" :class="{ 类名1: 布尔值, 类名2: 布尔值 }"></div>

​ 适用场景:一个类名,来回切换

3.数组语法

当class动态绑定的是数组时 → 数组中所有的类,都会添加到盒子上,本质就是一个 class 列表

<div class="box" :class="[ 类名1, 类名2, 类名3 ]"></div>

使用场景:  批量添加或删除类

4.代码练习

<style>
    .box {
      width: 200px;
      height: 200px;
      border: 3px solid #000;
      font-size: 30px;
      margin-top: 10px;
    }
    .pink {
      background-color: pink;
    }
    .big {
      width: 300px;
      height: 300px;
    }
  </style>


<div id="app">
    <!--绑定对象-->
    <div class="box">黑马程序员</div>
    <!--绑定数组-->
    <div class="box">黑马程序员</div>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {

      }
    })
  </script>

✍🏻案例:京东秒杀-tab栏切换导航高亮

1.需求:

当我们点击哪个tab页签时,哪个tab页签就高亮

案例解析:

核心思路:

  • 基于数据动态渲染tab ——>  v-for
  • 准备下标记录高亮的是哪一个 tab ——>activelndex
  • 基于下标,动态控制class 类名——> v-bind:class

 所谓切换高亮其实就是改下标

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    ul {
      display: flex;
      border-bottom: 2px solid #e01222;
      padding: 0 10px;
    }
    li {
      width: 100px;
      height: 50px;
      line-height: 50px;
      list-style: none;
      text-align: center;
    }
    li a {
      display: block;
      text-decoration: none;
      font-weight: bold;
      color: #333333;
    }
    li a.active {
      background-color: #e01222;
      color: #fff;
    }

  </style>
</head>
<body>

  <div id="app">
    <ul>
      <li v-for="(item, index) in list" :key="item.id" @click="activeIndex = index">
        <a :class="{ active: index === activeIndex }" href="#">{{ item.name }}</a>
      </li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        activeIndex: 2, // 记录高亮
        list: [
          { id: 1, name: '京东秒杀' },
          { id: 2, name: '每日特价' },
          { id: 3, name: '品类秒杀' }
        ]
      }
    })
  </script>
</body>
</html>

2️⃣操作style

1.语法:

<div class="box" :style="{ CSS属性名1: CSS属性值, CSS属性名2: CSS属性值 }"></div>
<style>
    .box {
      width: 200px;
      height: 200px;
      background-color: rgb(187, 150, 156);
    }
 </style>
 <div id="app">
    <div class="box"></div>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {

      }
    })
  </script>

2.案例:进度条百分比变化

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .progress {
      height: 25px;
      width: 400px;
      border-radius: 15px;
      background-color: #272425;
      border: 3px solid #272425;
      box-sizing: border-box;
      margin-bottom: 30px;
    }
    .inner {
      width: 50%;
      height: 20px;
      border-radius: 10px;
      text-align: right;
      position: relative;
      background-color: #409eff;
      background-size: 20px 20px;
      box-sizing: border-box;
      transition: all 1s;
    }
    .inner span {
      position: absolute;
      right: -20px;
      bottom: -25px;
    }
  </style>
</head>
<body>
  <div id="app">
    <!-- 外层盒子底色 (黑色) -->
    <div class="progress">
      <!-- 内层盒子 - 进度(蓝色) -->
      <div class="inner" :style="{ width: percent + '%' }">
        <span>{{ percent }}%</span>
      </div>
    </div>
    <button @click="percent = 25">设置25%</button>
    <button @click="percent = 50">设置50%</button>
    <button @click="percent = 75">设置75%</button>
    <button @click="percent = 100">设置100%</button>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        percent: 30
      }
    })
  </script>
</body>
</html>

3.适用场景:  某个具体属性的动态设置


3.v-model在其他表单元素的使用

常见的表单元素都可以用 v-model 绑定关联 → 快速 获取 或 设置 表单元素的值

它会根据 控件类型 自动选取 正确的方法 来更新元素

输入框  input:text   ——> value
文本域  textarea	 ——> value
复选框  input:checkbox  ——> checked
单选框  input:radio   ——> checked
下拉菜单 select    ——> value
...

check 单选框 前置理解:
1.name :给单选框加上 name 属性 可以分组  同一组互相会互斥

2.value: 给单选框加上 value 属性,用于提交给后台的数据

select 多选框 前置理解:
1.option 需要设置value 值,提交给后台
2.select 的 value 关联了选中的 option 的 value 值

代码示例:

<style>
    textarea {
      display: block;
      width: 240px;
      height: 100px;
      margin: 10px 0;
    }
  </style>
 <div id="app">
    <h3>学习网</h3>
    姓名:
      <input type="text"> 
      <br><br>
    是否单身:
      <input type="checkbox"> 
      <br><br>
    <!-- 
      前置理解:
        1. name:  给单选框加上 name 属性 可以分组 → 同一组互相会互斥
        2. value: 给单选框加上 value 属性,用于提交给后台的数据
      结合 Vue 使用 → v-model
    -->
    性别: 
      <input type="radio">男
      <input type="radio">女
      <br><br>
    <!-- 
      前置理解:
        1. option 需要设置 value 值,提交给后台
        2. select 的 value 值,关联了选中的 option 的 value 值
      结合 Vue 使用 → v-model
    -->
    所在城市:
      <select>
        <option>北京</option>
        <option>上海</option>
        <option>成都</option>
        <option>南京</option>
      </select>
      <br><br>
    自我描述:
      <textarea></textarea> 
    <button>立即注册</button>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {

      }
    })
  </script>


四、computed计算属性

1.概念:

基于现有的数据,计算出来的新属性。 依赖的数据变化,自动重新计算。

2.语法:

  1. 声明在 computed 配置项 中,一个计算属性对应一个函数
  2. 使用起来和普通属性一样使用 {{ 计算属性名 }}

简单理解为  计算属性——>可以将一段 求值的代码 进行封装

⭕3.注意:

  1. computed配置项和data配置项是同级
  2. computed中的计算属性虽然是函数的写法,但他依然是个属性(即不用加括号)
  3. computed中的计算属性不能和data中的属性同名
  4. 使用computed中的计算属性和使用data中的属性是一样的用法
  5. computed中计算属性内部的this依然指向的是Vue实例

案例:

使用计算属性实现下面这个业务场景

代码实现: 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table {
      border: 1px solid #000;
      text-align: center;
      width: 240px;
    }
    th,td {
      border: 1px solid #000;
    }
    h3 {
      position: relative;
    }
  </style>
</head>
<body>

  <div id="app">
    <h3>小黑的礼物清单</h3>
    <table>
      <tr>
        <th>名字</th>
        <th>数量</th>
      </tr>
      <tr v-for="(item, index) in list" :key="item.id">
        <td>{{ item.name }}</td>
        <td>{{ item.num }}个</td>
      </tr>
    </table>

    <!-- 目标:统计求和,求得礼物总数 -->
    <p>礼物总数:{{ totalCount }} 个</p>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        // 现有的数据
        list: [
          { id: 1, name: '篮球', num: 1 },
          { id: 2, name: '玩具', num: 2 },
          { id: 3, name: '铅笔', num: 5 },
        ]
      },
      computed: {
        totalCount () {
          // 基于现有的数据,编写求值逻辑
          // 计算属性函数内部,可以直接通过 this 访问到 app 实例
          // console.log(this.list)

          // 需求:对 this.list 数组里面的 num 进行求和 → reduce
          let total = this.list.reduce((sum, item) => sum + item.num, 0)
          return total
        }
      }
    })
  </script>
</body>
</html>

reduce 函数 简介

语法:array.reduce(callback[, initialValue])

  • array: 要操作的数组。
  • callback: 一个回调函数,用于处理每个数组元素。它可以接收四个参数:
    • accumulator (累加器): 保存归约过程中的结果。
    • currentValue (当前值): 当前迭代的数组元素。
    • currentIndex (当前索引) [可选]: 当前元素在数组中的索引。
    • array (数组) [可选]: 被 reduce() 方法调用的数组。
  • initialValue (初始值) [可选]: 可以指定归约过程的初始值。如果未指定此参数,reduce() 将从数组的第一个元素开始迭代,并将第一个元素作为初始值。

例1:求数组元素的和

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
// 结果为 15

例2:拼接数组中的字符串元素:

const strings = ['Hello', ' ', 'World', '!'];
const concatenatedString = strings.reduce((accumulator, currentValue) => accumulator + currentValue, '');
// 结果为 'Hello World!'

例3:计算数组元素的平均值:

const values = [10, 20, 30, 40, 50];
const average = values.reduce((accumulator, currentValue, currentIndex, array) => {
  accumulator += currentValue;
  if (currentIndex === array.length - 1) {
    return accumulator / array.length;
  }
  return accumulator;
}, 0);
// 结果为 30


1puted 计算属性 VS methods方法

1️⃣computed 计算属性

作用:封装了一段对于数据的处理,求得一个结果

语法:

  1. 写在computed配置项中
  2. 作为属性,直接使用
    • JS 中使用计算属性: this.计算属性
    • 模板中使用计算属性:{{计算属性}}

2️⃣ methods计算属性

作用:给Vue实例提供一个方法,调用以处理业务逻辑

语法:

  1. 写在methods配置项中
  2. 作为方法调用
    • JS 中调用:this.方法名()
    • 模板中调用 {{方法名()}} 或者 @事件名=“方法名”

计算属性的优势

  1. 缓存特性(提升性能)

    计算属性会对计算出来的结果缓存,再次使用直接读取缓存

    依赖项变化了,会自动重新计算 → 并再次缓存

  2. methods没有缓存特性

  3. 通过代码比较

代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table {
      border: 1px solid #000;
      text-align: center;
      width: 300px;
    }
    th,td {
      border: 1px solid #000;
    }
    h3 {
      position: relative;
    }
    span {
      position: absolute;
      left: 145px;
      top: -4px;
      width: 16px;
      height: 16px;
      color: white;
      font-size: 12px;
      text-align: center;
      border-radius: 50%;
      background-color: #e63f32;
    }
  </style>
</head>
<body>

  <div id="app">
    <h3>小黑的礼物清单🛒<span>{{ totalCountFn() }}</span></h3>
    <h3>小黑的礼物清单🛒<span>{{ totalCountFn() }}</span></h3>
    <h3>小黑的礼物清单🛒<span>{{ totalCountFn() }}</span></h3>
    <h3>小黑的礼物清单🛒<span>{{ totalCountFn() }}</span></h3>
    <table>
      <tr>
        <th>名字</th>
        <th>数量</th>
      </tr>
      <tr v-for="(item, index) in list" :key="item.id">
        <td>{{ item.name }}</td>
        <td>{{ item.num }}个</td>
      </tr>
    </table>

    <p>礼物总数:{{ totalCountFn() }} 个</p>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        // 现有的数据
        list: [
          { id: 1, name: '篮球', num: 3 },
          { id: 2, name: '玩具', num: 2 },
          { id: 3, name: '铅笔', num: 5 },
        ]
      },

      methods: {
        totalCountFn () {
          console.log('methods方法执行了')
          let total = this.list.reduce((sum, item) => sum + item.num, 0)
          return total
        }
      },

      computed: {
        // 计算属性:有缓存的,一旦计算出来结果,就会立刻缓存
        // 下一次读取 → 直接读缓存就行 → 性能特别高
        // totalCount () {
        //   console.log('计算属性执行了')
        //   let total = this.list.reduce((sum, item) => sum + item.num, 0)
        //   return total
        // }
      }
    })
  </script>
</body>
</html>

总结:

1puted有缓存特性,methods没有缓存

2.当一个结果依赖其他多个值时,推荐使用计算属性

3.当处理业务逻辑时,推荐使用 methods 方法,比如事件的处理函数


2.计算属性的完整写法

既然计算属性也是属性,能访问,应该也能修改了?

  1. 计算属性默认的简写,只能读取访问,不能 "修改"
  2. 如果要 "修改" → 需要写计算属性的完整写法

 代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    input {
      width: 30px;
    }
  </style>
</head>
<body>

  <div id="app">
    姓:<input type="text" v-model="firstName"> +
    名:<input type="text" v-model="lastName"> =
    <span>{{ fullName }}</span><br><br>
    
    <button @click="changeName">改名卡</button>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        firstName: '刘',
        lastName: '备',
      },
      methods: {
        changeName () {
          this.fullName = '黄忠'
        }
      },
      computed: {
        // 简写 → 获取,没有配置设置的逻辑
        // fullName () {
        //   return this.firstName + this.lastName
        // }

        // 完整写法 → 获取 + 设置
        fullName: {
          // (1) 当fullName计算属性,被获取求值时,执行get(有缓存,优先读缓存)
          //     会将返回值作为,求值的结果
          get () {
            return this.firstName + this.lastName
          },
          // (2) 当fullName计算属性,被修改赋值时,执行set
          //     修改的值,传递给set方法的形参
          set (value) {
            // console.log(value.slice(0, 1))          
            // console.log(value.slice(1))         
            this.firstName = value.slice(0, 1)
            this.lastName = value.slice(1)
          }
        }
      }
    })
  </script>
</body>
</html>

splice()方法 简介

语法如下:

array.splice(start, deleteCount, item1, item2, ...);
  • start: 必需,表示开始修改的索引位置,可以是正数或负数。
  • deleteCount: 可选,表示要删除的元素数量。如果为0,则不删除任何元素。
  • item1, item2, ...: 可选,表示要添加到数组的元素。可以添加一个或多个元素。

splice()方法的功能

  1. 删除元素:通过将deleteCount设置为大于0的值,可以从数组中删除一定数量的元素。从start索引开始的deleteCount个元素将被移除。
  2. 替换元素:通过设置deleteCount大于0并提供新元素,可以删除一定数量的元素并在start索引处插入新元素。
  3. 插入元素:通过将deleteCount设置为0,并提供新元素,可以在start索引处插入新元素,不会删除任何元素。

示例:

假设有以下数组:

let fruits = ['apple', 'banana', 'orange', 'grape'];

1️⃣删除元素:

let removedItems = fruits.splice(1, 2);
// 现在fruits数组为['apple', 'grape']
// removedItems数组为['banana', 'orange']

2️⃣替换元素:

let replacedItems = fruits.splice(1, 2, 'kiwi', 'cherry');
// 现在fruits数组为['apple', 'kiwi', 'cherry', 'grape']
// replacedItems数组为['banana', 'orange']

3️⃣插入元素:

fruits.splice(1, 0, 'kiwi', 'cherry');
// 现在fruits数组为['apple', 'kiwi', 'cherry', 'banana', 'orange', 'grape']

⭕注意:在使用splice()方法时,原始数组会被修改,而且它是原地操作,没有创建新的数组。因此,执行该方法后,原数组将被更改。


✍🏻综合案例-成绩案例 

功能描述:

1.渲染功能

2.删除功能

3.添加功能

4.统计总分,求平均分( toFixed() 是Number对象的一个方法,用于将数字格式化为指定小数位数的字符串表示。)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./styles/index.css" />
    <title>Document</title>
  </head>
  <body>
    <div id="app" class="score-case">
      <div class="table">
        <table>
          <thead>
            <tr>
              <th>编号</th>
              <th>科目</th>
              <th>成绩</th>
              <th>操作</th>
            </tr>
          </thead>

          <tbody v-if="list.length > 0">
            <tr v-for="(item, index) in list" :key="item.id">
              <td>{{ index + 1 }}</td>
              <td>{{ item.subject }}</td>
              <!-- 需求:不及格的标红, < 60 分, 加上 red 类 -->
              <td :class="{ red: item.score < 60 }">{{ item.score }}</td>
              <td><a @click.prevent="del(item.id)" href="http://www.baidu">删除</a></td>
            </tr>
          </tbody>

          <tbody v-else>
            <tr>
              <td colspan="5">
                <span class="none">暂无数据</span>
              </td>
            </tr>
          </tbody>

          <tfoot>
            <tr>
              <td colspan="5">
                <span>总分:{{ totalScore }}</span>
                <span style="margin-left: 50px">平均分:{{ averageScore }}</span>
              </td>
            </tr>
          </tfoot>
        </table>
      </div>
      <div class="form">
        <div class="form-item">
          <div class="label">科目:</div>
          <div class="input">
            <input
              type="text"
              placeholder="请输入科目"
              v-model.trim="subject"
            />
          </div>
        </div>
        <div class="form-item">
          <div class="label">分数:</div>
          <div class="input">
            <input
              type="text"
              placeholder="请输入分数"
              v-model.number="score"
            />
          </div>
        </div>
        <div class="form-item">
          <div class="label"></div>
          <div class="input">
            <button @click="add" class="submit" >添加</button>
          </div>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>

    <script>
      const app = new Vue({
        el: '#app',
        data: {
          list: [
            { id: 1, subject: '语文', score: 62 },
            { id: 7, subject: '数学', score: 89 },
            { id: 12, subject: '英语', score: 70 },
          ],
          subject: '',
          score: ''
        },
        computed: {
          totalScore() {
            return this.list.reduce((sum, item) => sum + item.score, 0)
          },
          averageScore () {
            if (this.list.length === 0) {
              return 0
            }
            return (this.totalScore / this.list.length).toFixed(2)
          }
        },
        methods: {
          del (id) {
            // console.log(id)
            this.list = this.list.filter(item => item.id !== id)
          },
          add () {
            if (!this.subject) {
              alert('请输入科目')
              return
            }
            if (typeof this.score !== 'number') {
              alert('请输入正确的成绩')
              return
            }
            this.list.unshift({
              id: +new Date(),
              subject: this.subject,
              score: this.score
            })

            this.subject = ''
            this.score = ''
          }
        }
      })
    </script>
  </body>
</html>

业务技术点总结:
1.渲染功能(不及格高亮)

  1. v-if
  2. v-else
  3. v-for
  4. v-bind:class

2.删除功能
点击传参 filter过滤覆盖原数组
.prevent 阻止默认行为


3.添加功能
v-model   v-model修饰符(.trim .number)
unshift 修改数组更新视图

4.统计总分,求平均分
计算属性  reduce求和


五、watch侦听器(监视器)

1.作用:

​ 监视数据变化,执行一些业务逻辑或异步操作

2.语法:

  1. watch同样声明在跟data同级的配置项中

  2. 简单写法: 简单类型数据直接监视

  3. 完整写法:添加额外配置项

 

 代码示例:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-size: 18px;
      }
      #app {
        padding: 10px 20px;
      }
      .query {
        margin: 10px 0;
      }
      .box {
        display: flex;
      }
      textarea {
        width: 300px;
        height: 160px;
        font-size: 18px;
        border: 1px solid #dedede;
        outline: none;
        resize: none;
        padding: 10px;
      }
      textarea:hover {
        border: 1px solid #1589f5;
      }
      .transbox {
        width: 300px;
        height: 160px;
        background-color: #f0f0f0;
        padding: 10px;
        border: none;
      }
      .tip-box {
        width: 300px;
        height: 25px;
        line-height: 25px;
        display: flex;
      }
      .tip-box span {
        flex: 1;
        text-align: center;
      }
      .query span {
        font-size: 18px;
      }

      .input-wrap {
        position: relative;
      }
      .input-wrap span {
        position: absolute;
        right: 15px;
        bottom: 15px;
        font-size: 12px;
      }
      .input-wrap i {
        font-size: 20px;
        font-style: normal;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <!-- 条件选择框 -->
      <div class="query">
        <span>翻译成的语言:</span>
        <select>
          <option value="italy">意大利</option>
          <option value="english">英语</option>
          <option value="german">德语</option>
        </select>
      </div>

      <!-- 翻译框 -->
      <div class="box">
        <div class="input-wrap">
          <textarea v-model="obj.words"></textarea>
          <span><i>⌨️</i>文档翻译</span>
        </div>
        <div class="output-wrap">
          <div class="transbox">mela</div>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr/npm/axios/dist/axios.min.js"></script>
    <script>
      // 接口地址:https://applet-base-api-t.itheima/api/translate
      // 请求方式:get
      // 请求参数:
      // (1)words:需要被翻译的文本(必传)
      // (2)lang: 需要被翻译成的语言(可选)默认值-意大利
      // -----------------------------------------------
      
      const app = new Vue({
        el: '#app',
        data: {
          // words: ''
          obj: {
            words: ''
          }
        },
        // 具体讲解:(1) watch语法 (2) 具体业务实现
        watch: {
          // 该方法会在数据变化时调用执行
          // newValue新值, oldValue老值(一般不用)
          // words (newValue) {
          //   console.log('变化了', newValue)
          // }

          'obj.words' (newValue) {
            console.log('变化了', newValue)
          }
        }
      })
    </script>
  </body>
</html>

功能实现:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-size: 18px;
      }
      #app {
        padding: 10px 20px;
      }
      .query {
        margin: 10px 0;
      }
      .box {
        display: flex;
      }
      textarea {
        width: 300px;
        height: 160px;
        font-size: 18px;
        border: 1px solid #dedede;
        outline: none;
        resize: none;
        padding: 10px;
      }
      textarea:hover {
        border: 1px solid #1589f5;
      }
      .transbox {
        width: 300px;
        height: 160px;
        background-color: #f0f0f0;
        padding: 10px;
        border: none;
      }
      .tip-box {
        width: 300px;
        height: 25px;
        line-height: 25px;
        display: flex;
      }
      .tip-box span {
        flex: 1;
        text-align: center;
      }
      .query span {
        font-size: 18px;
      }

      .input-wrap {
        position: relative;
      }
      .input-wrap span {
        position: absolute;
        right: 15px;
        bottom: 15px;
        font-size: 12px;
      }
      .input-wrap i {
        font-size: 20px;
        font-style: normal;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <!-- 条件选择框 -->
      <div class="query">
        <span>翻译成的语言:</span>
        <select>
          <option value="italy">意大利</option>
          <option value="english">英语</option>
          <option value="german">德语</option>
        </select>
      </div>

      <!-- 翻译框 -->
      <div class="box">
        <div class="input-wrap">
          <textarea v-model="obj.words"></textarea>
          <span><i>⌨️</i>文档翻译</span>
        </div>
        <div class="output-wrap">
          <div class="transbox">{{ result }}</div>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr/npm/axios/dist/axios.min.js"></script>
    <script>
      // 接口地址:https://applet-base-api-t.itheima/api/translate
      // 请求方式:get
      // 请求参数:
      // (1)words:需要被翻译的文本(必传)
      // (2)lang: 需要被翻译成的语言(可选)默认值-意大利
      // -----------------------------------------------
      
      const app = new Vue({
        el: '#app',
        data: {
          // words: ''
          obj: {
            words: ''
          },
          result: '', // 翻译结果
          // timer: null // 延时器id
        },
        // 具体讲解:(1) watch语法 (2) 具体业务实现
        watch: {
          // 该方法会在数据变化时调用执行
          // newValue新值, oldValue老值(一般不用)
          // words (newValue) {
          //   console.log('变化了', newValue)
          // }

          'obj.words' (newValue) {
            // console.log('变化了', newValue)
            // 防抖: 延迟执行 → 干啥事先等一等,延迟一会,一段时间内没有再次触发,才执行
            clearTimeout(this.timer)
            this.timer = setTimeout(async () => {
              const res = await axios({
                url: 'https://applet-base-api-t.itheima/api/translate',
                params: {
                  words: newValue
                }
              })
              this.result = res.data.data
              console.log(res.data.data)
            }, 300)
          }
        }
      })
    </script>
  </body>
</html>
  • clearTimeout()
  • 当使用 clearTimeout() 时,要确保传递正确的定时器ID。如果传递一个未定义的或者已经触发过的ID,clearTimeout()将不会产生任何效果。
  • 定时器ID在定时器创建时由setTimeout()返回,因此请妥善保存该ID以便后续取消定时器使用。
  • 使用clearTimeout()是一种良好的编程实践,可以避免不必要的定时器触发和资源浪费。

async函数
在函数前面加上async关键
字,该函数就成为一个异步函数。异步函数将隐式返回一个Promise对象,并且可以在函数内部使用await关键字来暂停执行,直到异步操作完成。


watch侦听器完整写法

1.语法:

完整写法 —>添加额外的配置项(将方法改写为对象)

  1. deep:true 对复杂类型进行深度监听
  2. immdiate:true 初始化 立刻执行一次
  3. handle:watch中需要具体执行的方法。
data: {
  obj: {
    words: '苹果',
    lang: 'italy'
  },
},

watch: {// watch 完整写法
  对象: {
    deep: true, // 深度监视
    immdiate:true,//立即执行handler函数
    handler (newValue) {
      console.log(newValue)
    }
  }
}

 2.需求:

  • 当文本框输入的时候 右侧翻译内容要时时变化
  • 当下拉框中的语言发生变化的时候 右侧翻译的内容依然要时时变化(实时翻译)
  • 如果文本框中有默认值的话要立即翻译

 3.代码实现:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-size: 18px;
      }
      #app {
        padding: 10px 20px;
      }
      .query {
        margin: 10px 0;
      }
      .box {
        display: flex;
      }
      textarea {
        width: 300px;
        height: 160px;
        font-size: 18px;
        border: 1px solid #dedede;
        outline: none;
        resize: none;
        padding: 10px;
      }
      textarea:hover {
        border: 1px solid #1589f5;
      }
      .transbox {
        width: 300px;
        height: 160px;
        background-color: #f0f0f0;
        padding: 10px;
        border: none;
      }
      .tip-box {
        width: 300px;
        height: 25px;
        line-height: 25px;
        display: flex;
      }
      .tip-box span {
        flex: 1;
        text-align: center;
      }
      .query span {
        font-size: 18px;
      }

      .input-wrap {
        position: relative;
      }
      .input-wrap span {
        position: absolute;
        right: 15px;
        bottom: 15px;
        font-size: 12px;
      }
      .input-wrap i {
        font-size: 20px;
        font-style: normal;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <!-- 条件选择框 -->
      <div class="query">
        <span>翻译成的语言:</span>
        <select v-model="obj.lang">
          <option value="italy">意大利</option>
          <option value="english">英语</option>
          <option value="german">德语</option>
        </select>
      </div>

      <!-- 翻译框 -->
      <div class="box">
        <div class="input-wrap">
          <textarea v-model="obj.words"></textarea>
          <span><i>⌨️</i>文档翻译</span>
        </div>
        <div class="output-wrap">
          <div class="transbox">{{ result }}</div>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr/npm/axios/dist/axios.min.js"></script>
    <script>
      // 需求:输入内容,修改语言,都实时翻译

      // 接口地址:https://applet-base-api-t.itheima/api/translate
      // 请求方式:get
      // 请求参数:
      // (1)words:需要被翻译的文本(必传)
      // (2)lang: 需要被翻译成的语言(可选)默认值-意大利
      // -----------------------------------------------
   
      const app = new Vue({
        el: '#app',
        data: {
          obj: {
            words: '小黑',
            lang: 'italy'
          },
          result: '', // 翻译结果
        },
        watch: {
          obj: {
            deep: true, // 深度监视
            immediate: true, // 立刻执行,一进入页面handler就立刻执行一次
            handler (newValue) {
              clearTimeout(this.timer)
              this.timer = setTimeout(async () => {
                const res = await axios({
                  url: 'https://applet-base-api-t.itheima/api/translate',
                  params: newValue
                })
                this.result = res.data.data
                console.log(res.data.data)
              }, 300)
            }
          }


          // 'obj.words' (newValue) {
          //   clearTimeout(this.timer)
          //   this.timer = setTimeout(async () => {
          //     const res = await axios({
          //       url: 'https://applet-base-api-t.itheima/api/translate',
          //       params: {
          //         words: newValue
          //       }
          //     })
          //     this.result = res.data.data
          //     console.log(res.data.data)
          //   }, 300)
          // }
        }
      })
    </script>
  </body>
</html>

4.总结:

watch侦听器的写法有几种?

1️⃣简单写法:监视简单类型的变化

watch: {
  数据属性名 (newValue, oldValue) {
    一些业务逻辑 或 异步操作。 
  },
  '对象.属性名' (newValue, oldValue) {
    一些业务逻辑 或 异步操作。 
  }
}

2️⃣完整写法:添加额外的配置项(深度监视复杂类型,立刻执行)

watch: {// watch 完整写法
  数据属性名: {
    deep: true, // 深度监视(针对复杂类型)
    immediate: true, // 是否立刻执行一次handler
    handler (newValue) {
      console.log(newValue)
    }
  }
}


✍综合案例-购物车

需求说明:

  1. 渲染功能
  2. 删除功能
  3. 修改个数
  4. 全选反选
  5. 统计 选中的 总价 和 总数量
  6. 持久化到本地

实现思路:

1.基本渲染: v-for遍历、:class动态绑定样式

2.删除功能 : v-on 绑定事件,获取当前行的id

3.修改个数 : v-on绑定事件,获取当前行的id,进行筛选出对应的项然后增加或减少

4.全选反选

  1. 必须所有的小选框都选中,全选按钮才选中 → every
  2. 如果全选按钮选中,则所有小选框都选中
  3. 如果全选取消,则所有小选框都取消选中

声明计算属性,判断数组中的每一个checked属性的值,看是否需要全部选

5.统计 选中的 总价 和 总数量 :通过计算属性来计算选中的总价和总数量

6.持久化到本地: 在数据变化时都要更新下本地存储 watch

①箭头函数简介:

(parameter1, parameter2, ..., parameterN) => { statements }

特点:

  1. 简洁的语法:箭头函数可以更简洁地定义函数,省略了function关键字和大括号,使得代码更加紧凑。

  2. 没有自己的this值:箭头函数没有自己的this绑定,它会捕获其所在上下文的this值,并且在函数体内使用该值。这意味着箭头函数中的this与外部的上下文保持一致,不会受到调用方式的影响。

  3. 没有arguments对象:箭头函数也没有自己的arguments对象。如果需要访问传递给箭头函数的参数,可以使用剩余参数语法或结构赋值来获取参数。

  4. 不能用作构造函数:由于箭头函数没有自己的this值,因此不能使用new关键字来调用箭头函数作为构造函数创建实例对象。

// 无参数的箭头函数
const greet = () => {
  console.log("Hello!");
};

// 含有一个参数的箭头函数
const double = (num) => {
  return num * 2;
};

// 可以省略括号的单参数箭头函数
const square = num => num * num;

// 箭头函数可以作为回调函数使用
const numbers = [1, 2, 3];
const doubledNumbers = numbers.map(num => num * 2);

:disabled 属性用于禁用表单元素,比如按钮、输入框等,使其变为不可交互状态。

:disabled="item.num <= 1"


③find() 方法接受一个回调函数作为参数,该回调函数用于定义查找的条件。回调函数将被依次应用于数组中的每个元素,直到返回一个满足条件的元素。如果找到匹配的元素,则 find() 方法立即停止遍历,返回该元素;如果没有找到匹配的元素,则返回 undefined

语法:

array.find(callback[, thisArg])
  • callback:必需,表示在每个元素上触发的回调函数。它可以接受三个参数:

    • element:当前正在处理的元素。
    • index:当前正在处理的元素的索引。
    • array:调用该方法的数组。 这个回调函数必须返回一个布尔值,表示是否找到满足条件的元素。
  • thisArg(可选):执行回调函数时使用的 this 值。

  • 示例如下:

    // 定义一个数组
    const numbers = [1, 2, 3, 4, 5];
    
    // 使用 find() 方法查找大于 3 的第一个元素
    const result = numbers.find(function(element) {
      return element > 3;
    });
    
    console.log(result); // 输出: 4
    


④every() 方法接受一个回调函数作为参数,该回调函数在遍历数组的每个元素时被调用。回调函数将被依次应用于数组中的每个元素,直到返回一个非真值(例如 false)。如果所有元素都满足回调函数中定义的条件,则 every() 方法返回 true;否则,返回 false

// 假设有一个选项数组
const options = [
  { label: '选项1', selected: true },
  { label: '选项2', selected: false },
  { label: '选项3', selected: true },
  // ...
];

// 使用 every() 方法检查所有选项是否都被选中
const allSelected = options.every(function(option) {
  return option.selected;
});

if (allSelected) {
  console.log('所有选项都被选中!');
} else {
  console.log('有选项未被选中!');
}

代码实现: 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./css/inputnumber.css" />
    <link rel="stylesheet" href="./css/index.css" />
    <title>购物车</title>
  </head>
  <body>
    <div class="app-container" id="app">
      <!-- 顶部banner -->
      <div class="banner-box"><img src="http://autumnfish/static/fruit.jpg" alt="" /></div>
      <!-- 面包屑 -->
      <div class="breadcrumb">
        <span>🏠</span>
        /
        <span>购物车</span>
      </div>
      <!-- 购物车主体 -->
      <div class="main" v-if="fruitList.length > 0">
        <div class="table">
          <!-- 头部 -->
          <div class="thead">
            <div class="tr">
              <div class="th">选中</div>
              <div class="th th-pic">图片</div>
              <div class="th">单价</div>
              <div class="th num-th">个数</div>
              <div class="th">小计</div>
              <div class="th">操作</div>
            </div>
          </div>
          <!-- 身体 -->
          <div class="tbody">
            <div v-for="(item, index) in fruitList" :key="item.id" class="tr" :class="{ active: item.isChecked }">
              <div class="td"><input type="checkbox" v-model="item.isChecked" /></div>
              <div class="td"><img :src="item.icon" alt="" /></div>
              <div class="td">{{ item.price }}</div>
              <div class="td">
                <div class="my-input-number">
                  <button :disabled="item.num <= 1" class="decrease" @click="sub(item.id)"> - </button>
                  <span class="my-input__inner">{{ item.num }}</span>
                  <button class="increase" @click="add(item.id)"> + </button>
                </div>
              </div>
              <div class="td">{{ item.num * item.price }}</div>
              <div class="td"><button @click="del(item.id)">删除</button></div>
            </div>
          </div>
        </div>
        <!-- 底部 -->
        <div class="bottom">
          <!-- 全选 -->
          <label class="check-all">
            <input type="checkbox" v-model="isAll"/>
            全选
          </label>
          <div class="right-box">
            <!-- 所有商品总价 -->
            <span class="price-box">总价&nbsp;&nbsp;:&nbsp;&nbsp;¥&nbsp;<span class="price">{{ totalPrice }}</span></span>
            <!-- 结算按钮 -->
            <button class="pay">结算( {{ totalCount }} )</button>
          </div>
        </div>
      </div>
      <!-- 空车 -->
      <div class="empty" v-else>🛒空空如也</div>
    </div>
    <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
    <script>
      const defaultArr = [
            {
              id: 1,
              icon: 'http://autumnfish/static/火龙果.png',
              isChecked: true,
              num: 2,
              price: 6,
            },
            {
              id: 2,
              icon: 'http://autumnfish/static/荔枝.png',
              isChecked: false,
              num: 7,
              price: 20,
            },
            {
              id: 3,
              icon: 'http://autumnfish/static/榴莲.png',
              isChecked: false,
              num: 3,
              price: 40,
            },
            {
              id: 4,
              icon: 'http://autumnfish/static/鸭梨.png',
              isChecked: true,
              num: 10,
              price: 3,
            },
            {
              id: 5,
              icon: 'http://autumnfish/static/樱桃.png',
              isChecked: false,
              num: 20,
              price: 34,
            },
          ]
      const app = new Vue({
        el: '#app',
        data: {
          // 水果列表
          fruitList: JSON.parse(localStorage.getItem('list')) || defaultArr,
        },
        computed: {
          // 默认计算属性:只能获取不能设置,要设置需要写完整写法
          // isAll () {
          //   // 必须所有的小选框都选中,全选按钮才选中 → every
          //   return this.fruitList.every(item => item.isChecked)
          // }
          
          // 完整写法 = get + set
          isAll: {
            get () {
              return this.fruitList.every(item => item.isChecked)
            },
            set (value) {
              // 基于拿到的布尔值,要让所有的小选框 同步状态
              this.fruitList.forEach(item => item.isChecked = value)
            }
          },
          // 统计选中的总数 reduce
          totalCount () {
            return this.fruitList.reduce((sum, item) => {
              if (item.isChecked) {
                // 选中 → 需要累加
                return sum + item.num
              } else {
                // 没选中 → 不需要累加
                return sum
              }
            }, 0)
          },
          // 总计选中的总价 num * price
          totalPrice () {
            return this.fruitList.reduce((sum, item) => {
              if (item.isChecked) {
                return sum + item.num * item.price
              } else {
                return sum
              }
            }, 0)
          }
        },
        methods: {
          del (id) {
            this.fruitList = this.fruitList.filter(item => item.id !== id)
          },
          add (id) {
            // 1. 根据 id 找到数组中的对应项 → find
            const fruit = this.fruitList.find(item => item.id === id)
            // 2. 操作 num 数量
            fruit.num++
          },
          sub (id) {
            // 1. 根据 id 找到数组中的对应项 → find
            const fruit = this.fruitList.find(item => item.id === id)
            // 2. 操作 num 数量
            fruit.num--
          }
        },
        watch: {
          fruitList: {
            deep: true,
            handler (newValue) {
              //🌟 需要将变化后的 newValue 存入本地 (转JSON)
              localStorage.setItem('list', JSON.stringify(newValue))
            }
          }
        }
      })
    </script>
  </body>
</html>


接下来学习任务如下:

六、生命周期以及四个阶段

思考:

什么时候可以发送初始化渲染请求?(越早越好)

什么时候可以开始操作dom?(至少dom得渲染出来)

Vue生命周期:就是一个Vue实例从 创建销毁 的整个过程。

生命周期四个阶段:① 创建 ② 挂载 ③ 更新 ④ 销毁

1.创建阶段:创建响应式数据

2.挂载阶段:渲染模板

3.更新阶段:修改数据,更新视图

4.销毁阶段:销毁Vue实例

Vue生命周期钩子

Vue生命周期过程中,会自动运行一些函数,被称为【生命周期钩子】→ 让开发者可以在【特定阶段】运行自己的代码。

代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="app">
    <h3>{{ title }}</h3>
    <div>
      <button @click="count--">-</button>
      <span>{{ count }}</span>
      <button @click="count++">+</button>
    </div>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      data: {
        count: 100,
        title: '计数器'
      },
      // 1. 创建阶段(准备数据)
      beforeCreate () {
        console.log('beforeCreate 响应式数据准备好之前', this.count)
      },
      created () {
        console.log('created 响应式数据准备好之后', this.count)
        // this.数据名 = 请求回来的数据
        // 可以开始发送初始化渲染的请求了
      },

      // 2. 挂载阶段(渲染模板)
      beforeMount () {
        console.log('beforeMount 模板渲染之前', document.querySelector('h3').innerHTML)
      },
      mounted () {
        console.log('mounted 模板渲染之后', document.querySelector('h3').innerHTML)
        // 可以开始操作dom了
      },

      // 3. 更新阶段(修改数据 → 更新视图)
      beforeUpdate () {
        console.log('beforeUpdate 数据修改了,视图还没更新', document.querySelector('span').innerHTML)
      },
      updated () {
        console.log('updated 数据修改了,视图已经更新', document.querySelector('span').innerHTML)
      },

      // 4. 卸载阶段
      beforeDestroy () {
        console.log('beforeDestroy, 卸载前')
        console.log('清除掉一些Vue以外的资源占用,定时器,延时器...')
      },
      destroyed () {
        console.log('destroyed,卸载后')
      }
    })
  </script>
</body>
</html>


1️⃣在created中发送数据

created: 响应式数据准备好了,可以开始发送初始化渲染请求。 

代码实现: 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      list-style: none;
    }
    .news {
      display: flex;
      height: 120px;
      width: 600px;
      margin: 0 auto;
      padding: 20px 0;
      cursor: pointer;
    }
    .news .left {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding-right: 10px;
    }
    .news .left .title {
      font-size: 20px;
    }
    .news .left .info {
      color: #999999;
    }
    .news .left .info span {
      margin-right: 20px;
    }
    .news .right {
      width: 160px;
      height: 120px;
    }
    .news .right img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  </style>
</head>
<body>

  <div id="app">
    <ul>
      <li v-for="(item, index) in list" :key="item.id" class="news">
        <div class="left">
          <div class="title">{{ item.title }}</div>
          <div class="info">
            <span>{{ item.source }}</span>
            <span>{{ item.time }}</span>
          </div>
        </div>
        <div class="right">
          <img :src="item.img" alt="">
        </div>
      </li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr/npm/axios/dist/axios.min.js"></script>
  <script>
    // 接口地址:http://hmajax.itheima/api/news
    // 请求方式:get
    const app = new Vue({
      el: '#app',
      data: {
        list: []
      },
      async created () {
        // 1. 发送请求获取数据
        const res = await axios.get('http://hmajax.itheima/api/news')
        // 2. 更新到 list 中,用于页面渲染 v-for
        this.list = res.data.data
      }
    })
  </script>
</body>
</html>

2️⃣在mounted中获取焦点

① 搜索框获取焦点案例:

mounted: 模板渲染完成,可以开始操作DOM了。

核心思路:

1.等输大框渲染出来

2.让输入框获取焦点


<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>示例-获取焦点</title>
  <!-- 初始化样式 -->
  <link rel="stylesheet" href="https://cdn.jsdelivr/npm/reset.css@2.0.2/reset.min.css">
  <!-- 核心样式 -->
  <style>
    html,
    body {
      height: 100%;
    }
    .search-container {
      position: absolute;
      top: 30%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
    }
    .search-container .search-box {
      display: flex;
    }
    .search-container img {
      margin-bottom: 30px;
    }
    .search-container .search-box input {
      width: 512px;
      height: 16px;
      padding: 12px 16px;
      font-size: 16px;
      margin: 0;
      vertical-align: top;
      outline: 0;
      box-shadow: none;
      border-radius: 10px 0 0 10px;
      border: 2px solid #c4c7ce;
      background: #fff;
      color: #222;
      overflow: hidden;
      box-sizing: content-box;
      -webkit-tap-highlight-color: transparent;
    }
    .search-container .search-box button {
      cursor: pointer;
      width: 112px;
      height: 44px;
      line-height: 41px;
      line-height: 42px;
      background-color: #ad2a27;
      border-radius: 0 10px 10px 0;
      font-size: 17px;
      box-shadow: none;
      font-weight: 400;
      border: 0;
      outline: 0;
      letter-spacing: normal;
      color: white;
    }
    body {
      background: no-repeat center /cover;
      background-color: #edf0f5;
    }
  </style>
</head>

<body>
<div class="container" id="app">
  <div class="search-container">
    <img src="https://www.itheima/images/logo.png" alt="">
    <div class="search-box">
      <input type="text" v-model="words" id="inp">
      <button>搜索一下</button>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      words: ''
    },
    // 核心思路:
    // 1. 等input框渲染出来 mounted 钩子
    // 2. 让input框获取焦点 inp.focus()
    mounted () {
      document.querySelector('#inp').focus()
    }
  })
</script>

</body>

</html>

②新闻列表案例: 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      list-style: none;
    }
    .news {
      display: flex;
      height: 120px;
      width: 600px;
      margin: 0 auto;
      padding: 20px 0;
      cursor: pointer;
    }
    .news .left {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      padding-right: 10px;
    }
    .news .left .title {
      font-size: 20px;
    }
    .news .left .info {
      color: #999999;
    }
    .news .left .info span {
      margin-right: 20px;
    }
    .news .right {
      width: 160px;
      height: 120px;
    }
    .news .right img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  </style>
</head>
<body>

  <div id="app">
    <ul>
      <li v-for="(item, index) in list" :key="item.id" class="news">
        <div class="left">
          <div class="title">{{ item.title }}</div>
          <div class="info">
            <span>{{ item.source }}</span>
            <span>{{ item.time }}</span>
          </div>
        </div>
        <div class="right">
          <img :src="item.img" alt="">
        </div>
      </li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr/npm/axios/dist/axios.min.js"></script>
  <script>
    // 接口地址:http://hmajax.itheima/api/news
    // 请求方式:get
    const app = new Vue({
      el: '#app',
      data: {
        list: []
      },
      async created () {
        // 1. 发送请求获取数据
        const res = await axios.get('http://hmajax.itheima/api/news')
        // 2. 更新到 list 中,用于页面渲染 v-for
        this.list = res.data.data
      }
    })
  </script>
</body>
</html>

总结:

四个阶段,八个钩子 ——> 三个常用 created,mounted,beforeDestroy


✍🏻案例-记账清单

1.需求图例:

2.需求分析:

  1. 基本渲染
  2. 添加功能
  3. 删除功能
  4. 饼图渲染

3.思路分析:

1️⃣基本渲染

  • 立刻发送请求获取数据 created
  • 拿到数据,存到data的响应式数据中
  • 结合数据,进行渲染 v-for
  • 消费统计 —> 计算属性

2️⃣添加功能

  • 收集表单数据 v-model,使用指令修饰符处理数据
  • 给添加按钮注册点击事件,对输入的内容做非空判断,发送请求
  • 请求成功后,对文本框内容进行清空
  • 重新渲染列表(后端获取的数据渲染到前端)

3️⃣删除功能

  • 注册点击事件,获取当前行的id
  • 根据 id 发送删除请求
  • 需要重新渲染

4️⃣饼图渲染

  • 初始化一个饼图 echarts.init(dom) mounted钩子中渲染
  • 根据数据试试更新饼图 echarts.setOptions({...})

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- CSS only -->
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
    />
    <style>
      .red {
        color: red!important;
      }
      .search {
        width: 300px;
        margin: 20px 0;
      }
      .my-form {
        display: flex;
        margin: 20px 0;
      }
      .my-form input {
        flex: 1;
        margin-right: 20px;
      }
      .table > :not(:first-child) {
        border-top: none;
      }
      .contain {
        display: flex;
        padding: 10px;
      }
      .list-box {
        flex: 1;
        padding: 0 30px;
      }
      .list-box  a {
        text-decoration: none;
      }
      .echarts-box {
        width: 600px;
        height: 400px;
        padding: 30px;
        margin: 0 auto;
        border: 1px solid #ccc;
      }
      tfoot {
        font-weight: bold;
      }
      @media screen and (max-width: 1000px) {
        .contain {
          flex-wrap: wrap;
        }
        .list-box {
          width: 100%;
        }
        .echarts-box {
          margin-top: 30px;
        }
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div class="contain">
        <!-- 左侧列表 -->
        <div class="list-box">

          <!-- 添加资产 -->
          <form class="my-form">
            <input v-model.trim="name" type="text" class="form-control" placeholder="消费名称" />
            <input v-model.number="price" type="text" class="form-control" placeholder="消费价格" />
            <button @click="add" type="button" class="btn btn-primary">添加账单</button>
          </form>

          <table class="table table-hover">
            <thead>
              <tr>
                <th>编号</th>
                <th>消费名称</th>
                <th>消费价格</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in list" :key="item.id">
                <td>{{ index + 1 }}</td>
                <td>{{ item.name }}</td>
                <td :class="{ red: item.price > 500 }">{{ item.price.toFixed(2) }}</td>
                <td><a @click="del(item.id)" href="javascript:;">删除</a></td>
              </tr>
            </tbody>
            <tfoot>
              <tr>
                <td colspan="4">消费总计: {{ totalPrice.toFixed(2) }}</td>
              </tr>
            </tfoot>
          </table>
        </div>
        
        <!-- 右侧图表 -->
        <div class="echarts-box" id="main"></div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr/npm/echarts@5.4.0/dist/echarts.min.js"></script>
    <script src="https://cdn.jsdelivr/npm/vue@2/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr/npm/axios/dist/axios.min.js"></script>
    <script>
      /**
       * 接口文档地址:
       * https://www.apifox/apidoc/shared-24459455-ebb1-4fdc-8df8-0aff8dc317a8/api-53371058
       * 
       * 功能需求:
       * 1. 基本渲染
       *    (1) 立刻发送请求获取数据 created
       *    (2) 拿到数据,存到data的响应式数据中
       *    (3) 结合数据,进行渲染 v-for
       *    (4) 消费统计 => 计算属性
       * 2. 添加功能
       *    (1) 收集表单数据 v-model
       *    (2) 给添加按钮注册点击事件,发送添加请求
       *    (3) 需要重新渲染
       * 3. 删除功能
       *    (1) 注册点击事件,传参传 id
       *    (2) 根据 id 发送删除请求
       *    (3) 需要重新渲染
       * 4. 饼图渲染
       *    (1) 初始化一个饼图 echarts.init(dom)  mounted钩子实现
       *    (2) 根据数据实时更新饼图 echarts.setOption({ ... })
       */
      const app = new Vue({
        el: '#app',
        data: {
          list: [],
          name: '',
          price: ''
        },
        computed: {
          totalPrice () {
            return this.list.reduce((sum, item) => sum + item.price, 0)
          }
        },
        created () {
          // const res = await axios.get('https://applet-base-api-t.itheima/bill', {
          //   params: {
          //     creator: '小黑'
          //   }
          // })
          // this.list = res.data.data

          this.getList()
        },
        mounted () {
          this.myChart = echarts.init(document.querySelector('#main'))
          this.myChart.setOption({
            // 大标题
            title: {
              text: '消费账单列表',
              left: 'center'
            },
            // 提示框
            tooltip: {
              trigger: 'item'
            },
            // 图例
            legend: {
              orient: 'vertical',
              left: 'left'
            },
            // 数据项
            series: [
              {
                name: '消费账单',
                type: 'pie',
                radius: '50%', // 半径
                data: [
                  // { value: 1048, name: '球鞋' },
                  // { value: 735, name: '防晒霜' }
                ],
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          })
        },

        methods: {
          async getList () {
            const res = await axios.get('https://applet-base-api-t.itheima/bill', {
              params: {
                creator: '小黑'
              }
            })
            this.list = res.data.data

            // 更新图表
            this.myChart.setOption({
              // 数据项
              series: [
                {
                  // data: [
                  //   { value: 1048, name: '球鞋' },
                  //   { value: 735, name: '防晒霜' }
                  // ]
                  data: this.list.map(item => ({ value: item.price, name: item.name}))
                }
              ]
            })
          },
          async add () {
            if (!this.name) {
              alert('请输入消费名称')
              return
            }
            if (typeof this.price !== 'number') {
              alert('请输入正确的消费价格')
              return
            }

            // 发送添加请求
            const res = await axios.post('https://applet-base-api-t.itheima/bill', {
              creator: '小黑',
              name: this.name,
              price: this.price
            })
            // 重新渲染一次
            this.getList()

            this.name = ''
            this.price = ''
          },
          async del (id) {
            // 根据 id 发送删除请求
            const res = await axios.delete(`https://applet-base-api-t.itheima/bill/${id}`)
            // 重新渲染
            this.getList()
          }
        }
      })
    </script>
  </body>
</html>

七、工程化开发和脚手架

1.开发Vue的两种方式

  • 核心包传统开发模式:基于html / css / js 文件,直接引入核心包,开发 Vue。
  • 工程化开发模式:基于构建工具(例如:webpack)的环境中开发Vue。

 

(1)工程化开发模式优点:

提高编码效率,比如使用JS新语法、Less/Sass、Typescript等通过webpack都可以编译成浏览器识别的ES3/ES5/CSS等

(2)工程化开发模式问题:

  • webpack配置不简单
  • 雷同的基础配置
  • 缺乏统一的标准

为了解决以上问题,所以我们需要一个工具,生成标准化的配置

2.脚手架 Vue CLI

基本介绍:

Vue CLI 是Vue官方提供的一个全局命令工具

可以帮助我们快速创建一个开发Vue项目的标准化基础架子。【集成了webpack配置】

好处:

  1. 开箱即用,零配置
  2. 内置babel等工具
  3. 标准化的webpack配置

使用步骤:

  1. 全局安装(只需安装一次即可) yarn global add @vue/cli 或者 npm i @vue/cli -g
  2. 查看vue/cli版本: vue --version
  3. 创建项目架子:vue create project-name(项目名不能使用中文)
  4. 启动项目:yarn serve 或者 npm run serve(命令不固定,找package.json)


八、项目目录介绍和运行流程 

1.项目目录介绍 

// 3.Vue实例化,提供render方法 ——> 基于App.vue创建结构渲染index.html
new Vue({
    // el:#app',作用: 和$mount('选择器')作用一致,用于指定Vue所管理容器
    // render: h => h(App)
    render: (createElement) => {
        createElement
    }
}).$mount('#app'

render函数用于生成虚拟DOM(Virtual DOM)并最终渲染到页面上。然而,有时候你可能需要直接使用render函数来手动创建虚拟DOM,这在一些高级场景下很有用。

render函数是一个接受createElement函数作为参数的函数,它返回一个描述DOM结构的虚拟DOM节点。这使得你可以使用JavaScript代码来构建界面,而不必使用模板。

2.运行流程 


九、组件化开发 

 组件化:一个页面可以拆分成一个个组件,每个组件有着自己独立的结构、样式、行为

​ 好处:便于维护,利于复用 → 提升开发效率

​ 组件分类:普通组件、根组件。

根组件:  整个应用最上层的组件,包裹所有普通小组件。

​ 比如:下面这个页面,可以把所有的代码都写在一个页面中,但是这样显得代码比较混乱,难易维护。咱们可以按模块进行组件划分。

根组件 App.vue

1.根组件介绍

整个应用最上层的组件,包裹所有普通小组件。

 2.App.vue 文件 (单文件组件) 的三个组成部分

  • 语法高亮插件

 

  • 三部分构成

    • template:结构 (有且只能一个根元素)
    • script: js逻辑
    • style: 样式 (可支持less,需要装包)

  • 让组件支持less

    (1) style标签,lang="less" 开启less功能

    (2) 装包: yarn add less less-loader -D 或者npm i less less-loader -D

 3.总结

  • 组件化优点、分类;
  • 根组件


十、普通组件的注册使用-局部注册

1.特点:

只能在注册的组件内使用

2.步骤:

  1. 创建.vue文件(三个组成部分)
  2. 在使用的组件内先导入再注册,最后使用

3.使用方式:

当成html标签使用即可 <组件名></组件名>

4.注意:

组件名规范 —> 大驼峰命名法, 如 HmHeader

5.语法:

// 导入需要注册的组件
import 组件对象 from '.vue文件路径'
import HmHeader from './components/HmHeader'

export default {  // 局部注册
  components: {
   '组件名': 组件对象,
    HmHeader:HmHeaer,
    HmHeader
  }
}

6.练习

在App组件中,完成以下练习。在App.vue中使用组件的方式完成下面布局

<template>
  <div class="App">
    <!-- 头部组件 -->
    <HmHeader></HmHeader>
    <!-- 主体组件 -->
    <HmMain></HmMain>
    <!-- 底部组件 -->
    <HmFooter></HmFooter>

    <!-- 如果 HmFooter + tab 出不来 → 需要配置 vscode
         设置中搜索 trigger on tab → 勾上
    -->
  </div>
</template>

<script>
import HmHeader from './components/HmHeader.vue'
import HmMain from './components/HmMain.vue'
import HmFooter from './components/HmFooter.vue'
export default {
  components: {
    // '组件名': 组件对象
    HmHeader: HmHeader,
    HmMain,
    HmFooter
  }
}
</script>

<style>
.App {
  width: 600px;
  height: 700px;
  background-color: #87ceeb;
  margin: 0 auto;
  padding: 20px;
}
</style>


十一、普通组件的注册使用-全局注册

1.特点:

全局注册的组件,在项目的任何组件中都能使用

2.步骤:

  1. 创建.vue组件(三个组成部分)
  2. main.js中进行全局注册

3.使用方式:

当成HTML标签直接使用  :  <组件名></组件名>

4.注意:

组件名规范 —> 大驼峰命名法, 如 HmHeader

5.语法:

Vueponent('组件名', 组件对象)

// 在您的 main.js(或类似的入口文件)中进行全局注册
import Vue from 'vue';
import App from './App.vue';
import MyGlobalComponent from './components/MyGlobalComponent.vue';

// 全局注册一个名为 MyGlobalComponent 的组件
Vueponent('my-global-component', MyGlobalComponent);

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

//Vueponent(组件名,组件对象)

📜总结

1.全局注册组件应该在哪个文件中注册以及语法是什么?

2.全局组件在项目中的任何一个组件中可不可以使用?

组件的注册使用:
①两种注册方式
1️⃣局部注册
(1)创建vue组件(单文件组件)
(2) 使用的组件内导入,并局部注册 components: { 组件名: 组件对象 }
2️⃣全局注册
(1)创建vue组件(单文件组件)
(2) main.js内导入,并全局注册 Vueponent(组件名,组件对象)


②使用:
<组件名></组件名>
技巧:
一般都用局部注册如果发现确实是通用组件,再抽离到全局


✍🏻综合案例——小兔仙购物

1.小兔仙首页启动项目演示

2.小兔仙组件拆分示意图

3.开发思路

  1. 分析页面,按模块拆分组件,搭架子 (局部或全局注册)

  2. 根据设计图,编写组件 html 结构 css 样式 (已准备好)

  3. 拆分封装通用小组件 (局部或全局注册)

    将来 → 通过 JS 动态渲染,实现功能

本文标签: 上手全套源码案例内容