概念:Vue (读音 /vjuː/,类似于 view) 是一套构建用户界面的渐进式框架。
基于数据渲染出用户可以看到的界面
所谓渐进式就是循序渐进,不一定非得把Vue中的所有API都学完才能开发Vue,可以学一点开发一点
所谓框架:就是一套完整的解决方案
所谓框架:就是一套完整的解决方案
举个栗子
如果把一个完整的项目比喻为一个装修好的房子,那么框架就是一个毛坯房。
我们只需要在“毛坯房”的基础上,增加功能代码即可。
提到框架,不得不提一下库。
下图是 库 和 框架的对比。
框架的特点:有一套必须让开发者遵守的规则或者约束
咱们学框架就是学习的这些规则 官网
我们已经知道了Vue框架可以 基于数据帮助我们渲染出用户界面,那应该怎么做呢?
比如就上面这个数据,基于提供好的msg 怎么渲染后右侧可展示的数据呢?
核心步骤(4步):
插值表达式是一种Vue的模板语法
我们可以用插值表达式渲染出Vue提供的数据
表达式:是可以被求值的代码,JS引擎会讲其计算出一个结果
以下的情况都是表达式:
money + 100
money - 100
money * 10
money / 10
price >= 100 ? '真贵':'还行'
obj.name
arr[0]
fn()
obj.fn()
插值表达式语法:{{ 表达式 }}
<h3>{{title}}<h3>
<p>{{nickName.toUpperCase()}}</p>
<p>{{age >= 18 ? '成年':'未成年'}}</p>
<p>{{obj.name}}</p>
<p>{{fn()}}</p>
1.在插值表达式中使用的数据 必须在data中进行了提供
<p>{{hobby}}</p> //如果在data中不存在 则会报错
2.支持的是表达式,而非语句,比如:if for ...
<p>{{if}}</p>
3.不能在标签属性中使用 {{ }} 插值 (插值表达式只能标签中间使用)
<p title="{{username}}">我是P标签</p>
简单理解就是数据变,视图对应变。
data中的数据, 最终会被添加到实例上
① 访问数据: “实例.属性名”
② 修改数据: “实例.属性名”= “值”
安装步骤:
安装之后可以F12后看到多一个Vue的调试面板
概念:指令(Directives)是 Vue 提供的带有 v- 前缀 的 特殊 标签属性。
为啥要学:提高程序员操作 DOM 的效率。
vue 中的指令按照不同的用途可以分为如下 6 大类:
指令是 vue 开发中最基础、最常用、最简单的知识点。
内容渲染指令用来辅助开发者渲染 DOM 元素的文本内容。常用的内容渲染指令有如下2 个:
<p v-text="uname">hello</p>
,意思是将 uame 值渲染到 p 标签中<p v-html="intro">hello</p>
,意思是将 intro 值渲染到 p 标签中代码演示:
<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>
条件判断指令,用来辅助开发者按需控制 DOM 的显示与隐藏。条件渲染指令有如下两个,分别是:
示例代码:
<div id="app">
<div class="box">我是v-show控制的盒子</div>
<div class="box">我是v-if控制的盒子</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
flag: false
}
})
</script>
示例代码:
<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.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
gender: 2,
score: 95
}
})
</script>
使用Vue时,如需为DOM注册事件,及其的简单,语法如下:
v-on:
简写为 @<div id="app">
<button @click="count--">-</button>
<span>{{ count }}</span>
<button v-on:click="count++">+</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
count: 100
}
})
</script>
<div id="app">
<button @click="change">切换显示隐藏</button>
<h1 v-show="isShow">黑马程序员</h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
isShow: true
},
methods: {
change(){
this.isShow = false
}
}
})
</script>
3.给事件处理函数传参
$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 @click="buyDrink(5)">可乐5元</button>
<button @click="buyDrink(10)">咖啡10元</button>
<button @click="buyDrink(8)">牛奶8元</button>
</div>
<p>银行卡余额:{{ money }}元</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
money: 100
},
methods: {
buyDrink(price) {
if (this.money >= price) {
this.money -= price;
console.log(`购买成功,花费${price}元`);
} else {
console.log('余额不足,无法购买');
}
}
}
});
</script>
比如,有一个图片,它的 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.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
imgUrl: './imgs/10-02.png',
msg: 'hello 波仔'
}
})
</script>
需求:默认展示数组中的第一张图片,点击上一页下一页来回切换数组中的图片
实现思路:
1.数组存储图片路径 [‘url1’,‘url2’,‘url3’,…]
2.可以准备个下标index 去数组中取图片地址。
3.通过v-bind给src绑定当前的图片地址
4.点击上一页下一页只需要修改下标的值即可
5.当展示第一张的时候,上一页按钮应该隐藏。展示最后一张的时候,下一页按钮应该隐藏
<div id="app">
<button @click="previousImage" :disabled="currentIndex === 0">上一页</button>
<div>
<img :src="list[currentIndex]" alt="">
</div>
<button @click="nextImage" :disabled="currentIndex === list.length - 1">下一页</button>
</div>
<script src="https://cdn.jsdelivr.net/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',
],
currentIndex: 0
},
methods: {
previousImage() {
if (this.currentIndex > 0) {
this.currentIndex--;
}
},
nextImage() {
if (this.currentIndex < this.list.length - 1) {
this.currentIndex++;
}
}
}
});
</script>
Vue 提供了 v-for 列表渲染指令,用来辅助开发者基于一个数组来循环渲染一个列表结构。
v-for 指令需要使用 (item, index) in arr
形式的特殊语法,其中:
此语法也可以遍历对象和数字
对于遍历对象,你可以使用 v-for 指令来实现。在 v-for 中,可以通过括号 ( ) 将对象的值、键和索引分别指定给变量。
<div v-for="(value, key, index) in object">{{ value }}</div>
上述代码将遍历对象 object,并将每个值赋给变量 value,每个键赋给变量 key,每个索引赋给变量 index。可以在模板中使用这些变量来展示对象的值。 至于遍历数字,可以使用类似的方式,但需要注意的是索引从 1 开始。因为在 Vue.js 的 v-for 中,索引从 0 开始计数。所以如果要遍历数字 1 到 10,可以使用下面的代码:
<p v-for="item in 10">{{ item }}</p>
上述代码将创建 10 个
元素,并将数字 1 到 10 分别赋给变量 item。你可以根据自己的需求来处理每个数字,在模板中进行展示或执行其他操作。
需求:
1.根据左侧数据渲染出右侧列表(v-for)
2.点击删除按钮时,应该把当前行从列表中删除(获取当前行的id,利用filter进行过滤)
准备代码:
<div id="app">
<h3>小黑的书架</h3>
<ul>
<li v-for="book in booksList" :key="book.id">
<span>{{ book.name }}</span>
<span>{{ book.author }}</span>
<button @click="deleteBook(book.id)">删除</button>
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/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: {
deleteBook(id) {
this.booksList = this.booksList.filter(book => book.id !== id)
}
}
})
</script>
语法: key=“唯一值”
作用:给列表项添加的唯一标识。便于Vue进行列表项的正确排序复用。
**为什么加key:**Vue 的默认行为会尝试原地修改元素(就地复用)
实例代码:
<ul>
<li v-for="(item, index) in booksList" :key="item.id">
<span>{{ item.name }}</span>
<span>{{ item.author }}</span>
<button @click="del(item.id)">删除</button>
</li>
</ul>
注意:
所谓双向绑定就是:
作用: 给表单元素(input、radio、select)使用,双向绑定数据,可以快速 获取 或 设置 表单元素内容
**语法:**v-model=“变量”
**需求:**使用双向绑定实现以下需求
<div id="app">
账户:<input type="text" v-model="username"> <br><br>
密码:<input type="password" v-model="password"> <br><br>
<button @click="login">登录</button>
<button @click="reset">重置</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
username: '',
password: ''
},
methods: {
login() {
console.log('账户:', this.username);
console.log('密码:', this.password);
},
reset() {
this.username = '';
this.password = '';
}
}
})
</script>
功能需求:
<div id="app">
<h3>小黑记事本</h3>
<div class="form-group">
<input type="text" v-model="content">
<button @click="add">添加</button>
<button @click="clear">清空</button>
</div>
<ul class="list-group">
<li v-for="(item, index) in notes" class="list-group-item">
<span>{{ item }}</span>
<button @click="remove(index)">删除</button>
</li>
</ul>
<div class="footer">总共有 {{ notes.length }} 条记录</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
content: '',
notes: []
},
methods: {
add() {
if (this.content.trim()) {
this.notes.push(this.content);
this.content = '';
}
},
remove(index) {
this.notes.splice(index, 1);
},
clear() {
this.notes = [];
}
}
})
</script>
所谓指令修饰符就是通过“.”指明一些指令后缀 不同的后缀封装了不同的处理操作 —> 简化代码
代码演示:
<div id="app">
<h3>@keyup.enter → 监听键盘回车事件</h3>
<input v-model="username" type="text" @keyup.enter="handleEnter">
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
username: ''
},
methods: {
handleEnter() {
console.log('回车事件触发');
console.log('输入框的值:', this.username);
}
}
})
</script>
<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.trim="username" type="text"><br>
年纪:<input v-model.number="age" type="text"><br>
<h3>@事件名.stop → 阻止冒泡</h3>
<div @click="fatherFn" class="father">
<div @click.stop="sonFn" class="son">儿子</div>
</div>
<h3>@事件名.prevent → 阻止默认行为</h3>
<a @click.prevent href="http://www.baidu.com">阻止默认行为</a>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
username: '',
age: '',
},
methods: {
fatherFn () {
alert('老父亲被点击了')
},
sonFn (e) {
alert('儿子被点击了')
}
}
})
</script>
为了方便开发者进行样式控制, Vue 扩展了 v-bind 的语法,可以针对 class 类名 和 style 行内样式 进行控制 。
<div> :class = "对象/数组">这是一个div</div>
当class动态绑定的是对象时,键就是类名,值就是布尔值,如果值是true,就有这个类,否则没有这个类
<div class="box" :class="{ 类名1: 布尔值, 类名2: 布尔值 }"></div>
适用场景:一个类名,来回切换
当class动态绑定的是数组时 → 数组中所有的类,都会添加到盒子上,本质就是一个 class 列表
<div class="box" :class="[ 类名1, 类名2, 类名3 ]"></div>
使用场景:批量添加或删除类
<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': true, 'pink': true }">黑马程序员</div>
<!-- 绑定数组 -->
<div :class="[ 'box', 'big' ]">黑马程序员</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
}
})
</script>
当我们点击哪个tab页签时,哪个tab页签就高亮
<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>
<div id="app">
<ul>
<li v-for="(item, index) in list" :key="item.id" @click="changeTab(index)">
<a :class="{ 'active': activeIndex === index }" href="#">{{ item.name }}</a>
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
list: [
{ id: 1, name: '京东秒杀' },
{ id: 2, name: '每日特价' },
{ id: 3, name: '品类秒杀' }
],
activeIndex: 0 // 默认高亮第一个页签
},
methods: {
changeTab(index) {
this.activeIndex = index; // 切换高亮的页签
}
}
})
</script>
1.基于数据,动态渲染tab(v-for)
2.准备一个下标 记录高亮的是哪一个 tab
3.基于下标动态切换class的类名
<div class="box" :style="{ CSS属性名1: CSS属性值, CSS属性名2: CSS属性值 }"></div>
使用了 boxColor 变量来控制盒子的背景颜色。通过动态绑定 :style ,并且传入一个对象,对象的键名为 CSS 属性名,键值为对应的 CSS 属性值。当 boxColor 的值改变时,盒子的背景颜色也会相应地改变。
<style>
.box {
width: 200px;
height: 200px;
background-color: rgb(187, 150, 156);
}
</style>
<div id="app">
<div class="box" :style="{ backgroundColor: boxColor }"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
boxColor: 'rgb(187, 150, 156)'
}
})
</script>
<style>
.progress {
height: 25px;
width: 400px;
border-radius: 15px;
background-color: #272425;
border: 3px solid #272425;
box-sizing: border-box;
margin-bottom: 30px;
}
.inner {
height: 100%;
border-radius: 10px;
text-align: right;
position: relative;
background-color: #409eff;
background-size: 20px 20px;
box-sizing: border-box;
transition: width 1s;
}
.inner span {
position: absolute;
right: -20px;
bottom: -25px;
}
</style>
<div id="app">
<div class="progress">
<div class="inner" :style="{ width: progress + '%' }">
<span>{{ progress }}%</span>
</div>
</div>
<button @click="setProgress(25)">设置25%</button>
<button @click="setProgress(50)">设置50%</button>
<button @click="setProgress(75)">设置75%</button>
<button @click="setProgress(100)">设置100%</button>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
progress: 0
},
methods: {
setProgress(value) {
this.progress = value;
}
}
})
</script>
常见的表单元素都可以用 v-model 绑定关联 → 快速 获取 或 设置 表单元素的值
它会根据 控件类型 自动选取 正确的方法 来更新元素
输入框 input:text ——> value
文本域 textarea ——> value
复选框 input:checkbox ——> checked
单选框 input:radio ——> checked
下拉菜单 select ——> value
...
<style>
textarea {
display: block;
width: 240px;
height: 100px;
margin: 10px 0;
}
</style>
<div id="app">
<h3>小黑学习网</h3>
姓名:
<input type="text" v-model="name">
<br><br>
是否单身:
<input type="checkbox" v-model="single">
<br><br>
<!--
前置理解:
1. name: 给单选框加上 name 属性 可以分组 → 同一组互相会互斥
2. value: 给单选框加上 value 属性,用于提交给后台的数据
结合 Vue 使用 → v-model
-->
性别:
<input type="radio" name="gender" value="男" v-model="gender">男
<input type="radio" name="gender" value="女" v-model="gender">女
<br><br>
<!--
前置理解:
1. option 需要设置 value 值,提交给后台
2. select 的 value 值,关联了选中的 option 的 value 值
结合 Vue 使用 → v-model
-->
所在城市:
<select v-model="city">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="成都">成都</option>
<option value="南京">南京</option>
</select>
<br><br>
自我描述:
<textarea v-model="description"></textarea>
<button @click="register">立即注册</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
name: '', // 保存姓名
single: false, // 是否单身
gender: '', // 保存性别
city: '', // 保存所在城市
description: '' // 保存自我描述
},
methods: {
register() {
console.log('姓名:', this.name);
console.log('是否单身:', this.single);
console.log('性别:', this.gender);
console.log('所在城市:', this.city);
console.log('自我描述:', this.description);
}
}
})
</script>
基于现有的数据,计算出来的新属性。 依赖的数据变化,自动重新计算。
比如我们可以使用计算属性实现下面这个业务场景
<style>
table {
border: 1px solid #000;
text-align: center;
width: 240px;
}
th, td {
border: 1px solid #000;
}
h3 {
position: relative;
}
</style>
<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>礼物总数:{{ total }}个</p>
</div>
<script src="https://cdn.jsdelivr.net/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: {
total() {
// 使用reduce方法计算总数
return this.list.reduce((sum, item) => sum + item.num, 0);
}
}
})
</script>
我添加了一个新的计算属性total,通过使用数组的reduce方法来计算所有礼物的数量总和。然后在页面中通过{{ total }}来显示总数。 运行代码后,你会看到页面上的礼物总数会动态地根据当前的礼物清单计算出来
作用:封装了一段对于数据的处理,求得一个结果
语法:
作用:给Vue实例提供一个方法,调用以处理业务逻辑。
语法:
<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>
<div id="app">
<h3>小黑的礼物清单🛒<span>?</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>礼物总数:{{ totalCount }} 个</p>
</div>
<script src="https://cdn.jsdelivr.net/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 },
]
},
computed: {
totalCount () {
let total = this.list.reduce((sum, item) => sum + item.num, 0)
return total
}
}
})
</script>
1.computed有缓存特性,methods没有缓存
2.当一个结果依赖其他多个值时,推荐使用计算属性
3.当处理业务逻辑时,推荐使用methods方法,比如事件的处理函数
既然计算属性也是属性,能访问,应该也能修改了?
完整写法代码演示
该代码实现了以下功能:
<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.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: '刘',
lastName: '备'
},
computed: {
fullName: {
get: function() {
return this.firstName + this.lastName;
},
set: function(newName) {
// 将新的fullName分解成firstName和lastName
var names = newName.split(' ');
this.firstName = names[0];
this.lastName = names[1];
}
}
},
methods: {
changeName: function() {
// 模拟改名卡
this.fullName = '关 羽';
}
}
})
</script>
在这个示例中,我通过添加set方法,使得计算属性fullName也可以通过赋值的方式来修改。当我修改fullName的值时,首先会触发set方法进行分解,然后更新firstName和lastName的值,并重新计算出fullName,从而实现了对数据的修改。
具体功能包括:
注意,为了优化代码的复用性,使用了两个辅助方法getSubjectTotal和getSubjectAverage来计算总分和平均分,以避免代码重复。
<div id="app">
<!-- 页面标题 -->
<h2>成绩管理系统</h2>
<!-- 数据表格 -->
<table>
<!-- 表头 -->
<thead>
<tr>
<th>姓名</th>
<th>语文成绩</th>
<th>数学成绩</th>
<th>英语成绩</th>
<th>操作</th>
</tr>
</thead>
<!-- 学生列表 -->
<tbody>
<!-- 遍历students数组,将每个学生的信息渲染到表格中 -->
<tr v-for="(student, index) in students" :key="index">
<td>{{ student.name }}</td>
<td>{{ student.chinese }}</td>
<td>{{ student.math }}</td>
<td>{{ student.english }}</td>
<td>
<a href="#" @click="deleteStudent(index)">删除</a>
</td>
</tr>
</tbody>
<!-- 统计数据 -->
<tfoot>
<!-- 总分 -->
<tr>
<th>总分</th>
<th>{{ totalScore.chinese }}</th>
<th>{{ totalScore.math }}</th>
<th>{{ totalScore.english }}</th>
<th></th>
</tr>
<!-- 平均分 -->
<tr>
<th>平均分</th>
<th>{{ averageScore.chinese }}</th>
<th>{{ averageScore.math }}</th>
<th>{{ averageScore.english }}</th>
<th></th>
</tr>
</tfoot>
</table>
<!-- 添加学生的表单 -->
<!-- 使用v-model指令绑定表单元素到data中的newStudent对象上,实现双向数据绑定 -->
<div>
<label>姓名:</label>
<input type="text" v-model.trim="newStudent.name" required>
<label>语文成绩:</label>
<input type="number" v-model.number="newStudent.chinese" required>
<label>数学成绩:</label>
<input type="number" v-model.number="newStudent.math" required>
<label>英语成绩:</label>
<input type="number" v-model.number="newStudent.english" required>
<!-- 使用v-bind指令绑定添加按钮的disabled状态到isInvalid计算属性上,实现表单验证功能 -->
<button @click="addStudent" :disabled="isInvalid">添加</button>
</div>
</div>
<!-- 引入Vue.js库 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
students: [
{ name: '张三', chinese: 80, math: 90, english: 85 },
{ name: '李四', chinese: 75, math: 85, english: 90 },
{ name: '王五', chinese: 85, math: 95, english: 80 }
],
newStudent: {
name: '',
chinese: null,
math: null,
english: null
}
},
computed: {
// 计算属性:计算每个科目的总分
totalScore: function() {
return {
chinese: this.getSubjectTotal('chinese'),
math: this.getSubjectTotal('math'),
english: this.getSubjectTotal('english')
};
},
// 计算属性:计算每个科目的平均分
averageScore: function() {
return {
chinese: this.getSubjectAverage('chinese'),
math: this.getSubjectAverage('math'),
english: this.getSubjectAverage('english')
};
},
// 计算属性:判断表单是否填写完整
isInvalid: function() {
return (
!this.newStudent.name ||
this.newStudent.chinese === null ||
this.newStudent.math === null ||
this.newStudent.english === null
);
}
},
methods: {
// 删除学生信息
deleteStudent: function(index) {
this.students.splice(index, 1);
},
// 添加新学生
addStudent: function() {
this.students.push({ ...this.newStudent });
// 清空表单数据
this.newStudent = {
name: '',
chinese: null,
math: null,
english: null
};
},
// 辅助方法:计算某个科目的总分
getSubjectTotal: function(subject) {
return this.students.reduce((total, student) => {
return total + student[subject];
}, 0);
},
// 辅助方法:计算某个科目的平均分
getSubjectAverage: function(subject) {
const total = this.getSubjectTotal(subject);
return total / this.students.length || 0;
}
}
});
</script>
**监视数据变化**,执行一些业务逻辑或异步操作
data: {
words: '苹果',
obj: {
words: '苹果'
}
},
watch: {
// 该方法会在数据变化时,触发执行
数据属性名 (newValue, oldValue) {
一些业务逻辑 或 异步操作。
},
'对象.属性名' (newValue, oldValue) {
一些业务逻辑 或 异步操作。
}
}
可以在文本框中输入待翻译文本,选择目标语言,然后点击"文档翻译"按钮进行翻译。翻译后的文本将显示在下方的翻译框中。
<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>
<div id="app">
<!-- 条件选择框 -->
<div class="query">
<span>翻译成的语言:</span>
<select v-model="selectedLang">
<option value="italy">意大利</option>
<option value="english">英语</option>
<option value="german">德语</option>
</select>
</div>
<!-- 翻译框 -->
<div class="box">
<div class="input-wrap">
<textarea v-model="words"></textarea>
<span><i @click="translateText">⌨️</i>文档翻译</span>
</div>
<div class="output-wrap">
<div class="transbox">{{ translatedText }}</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
words: '', // 输入的待翻译文本
selectedLang: 'italy', // 选择的目标语言
translatedText: '' // 翻译后的文本
},
methods: {
translateText() {
// 构建请求参数对象
const params = {
words: this.words.trim(),
lang: this.selectedLang
};
// 发送GET请求
axios
.get('https://applet-base-api-t.itheima.net/api/translate', { params })
.then(response => {
// 请求成功,更新翻译后的文本
this.translatedText = response.data.data;
})
.catch(error => {
// 请求失败,输出错误信息
console.error(error);
});
}
}
});
</script>
<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>
<div id="app">
<!-- 条件选择框 -->
<div class="query">
<span>翻译成的语言:</span>
<select v-model="selectedLang">
<option value="italy">意大利</option>
<option value="english">英语</option>
<option value="german">德语</option>
</select>
</div>
<!-- 翻译框 -->
<div class="box">
<div class="input-wrap">
<textarea v-model="words"></textarea>
<span><i @click="translateText">⌨️</i>文档翻译</span>
</div>
<div class="output-wrap">
<div class="transbox">{{ translatedText }}</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 接口地址:https://applet-base-api-t.itheima.net/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.net/api/translate',
params: {
words: newValue
}
})
this.result = res.data.data
console.log(res.data.data)
}, 300)
}
}
})
</script>
购物车案例
需求说明:
实现思路:
1.基本渲染: v-for遍历、:class动态绑定样式
2.删除功能 : v-on 绑定事件,获取当前行的id
3.修改个数 : v-on绑定事件,获取当前行的id,进行筛选出对应的项然后增加或减少
4.全选反选
声明计算属性,判断数组中的每一个checked属性的值,看是否需要全部选
5.统计 选中的 总价 和 总数量 :通过计算属性来计算选中的总价和总数量
6.持久化到本地: 在数据变化时都要更新下本地存储 watch
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-size: 14px;
font-family: '微软雅黑';
}
ul {
list-style: none;
}
#app {
width: 970px;
margin: 30px auto;
background-color: #fff;
padding: 20px;
border-radius: 3px;
box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.2);
}
h1 {
font-size: 24px;
font-weight: bold;
margin-bottom: 10px;
}
.clearfix::after {
content: '';
display: table;
clear: both;
}
.cart-header {
display: flex;
justify-content: space-between;
align-items: center;
height: 40px;
margin-bottom: 20px;
}
.cart-header label {
cursor: pointer;
margin-right: 10px;
}
.cart-header h2 {
font-size: 20px;
font-weight: bold;
}
.cart-header .btn-del-all {
cursor: pointer;
color: #f00;
text-decoration: underline;
}
table {
width: 100%;
border-collapse: collapse;
border-spacing: 0;
}
th, td {
text-align: center;
vertical-align: middle;
}
thead {
background-color: #f5f5f5;
}
tbody tr:nth-child(odd) {
background-color: #e9e9e9;
}
.cart-item {
height: 130px;
display: flex;
padding: 10px 10px 10px 20px;
}
.cart-item td {
width: 15%;
}
.cart-item td:first-child {
width: 5%;
}
.cart-item input[type="checkbox"] {
margin-right: 10px;
}
.cart-item .goods-pic {
width: 60px;
height: 60px;
border-radius: 2px;
overflow: hidden;
margin-right: 10px;
}
.cart-item .goods-pic img {
width: 100%;
height: auto;
}
.cart-item .goods-name {
font-size: 16px;
font-weight: bold;
margin-bottom: 10px;
}
.cart-item .goods-price {
font-size: 18px;
}
.cart-item .num-input {
width: 80px;
height: 28px;
border: 1px solid #ddd;
text-align: center;
outline: none;
font-size: 14px;
}
.cart-item .btn-del {
cursor: pointer;
color: #f00;
text-decoration: underline;
margin-left: 10px;
}
.cart-total {
margin-top: 20px;
height: 40px;
line-height: 40px;
text-align: right;
font-size: 16px;
font-weight: bold;
}
.cart-total span:first-child {
margin-right: 10px;
}
.cart-btn {
margin-top: 20px;
text-align: right;
}
.cart-btn button {
width: 120px;
height: 40px;
border-radius: 2px;
outline: none;
font-size: 16px;
font-weight: bold;
cursor: pointer;
margin-left: 20px;
}
.cart-btn button:first-child {
background-color: #f00;
color: #fff;
border: 1px solid #f00;
}
.cart-btn button:last-child {
background-color: #1589f5;
color: #fff;
border: 1px solid #1589f5;
}
</style>
<div id="app">
<div class="cart-header clearfix">
<label for="select-all">
<input type="checkbox" id="select-all" v-model="allChecked">
全选
</label>
<h2>购物车</h2>
<span class="btn-del-all" v-on:click="deleteAllCheckeds">删除选中商品</span>
</div>
<table>
<thead>
<tr>
<th></th>
<th>商品信息</th>
<th>单价(元)</th>
<th>数量</th>
<th>小计(元)</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<template v-for="(item, index) in cartData">
<tr class="cart-item clearfix">
<td><input type="checkbox" v-model="item.checked"></td>
<td class="clearfix">
<div class="goods-pic"><img :src="item.imgUrl" alt=""></div>
<div class="goods-name">{{ item.name }}</div>
</td>
<td>{{ item.price }}</td>
<td>
<button class="minus" v-on:click="changeCount(index, -1)">-</button>
<input type="number" class="num-input" v-model="item.count">
<button class="plus" v-on:click="changeCount(index, 1)">+</button>
</td>
<td>{{ item.count * item.price }}</td>
<td><span class="btn-del" v-on:click="deleteItem(index)">删除</span></td>
</tr>
</template>
</tbody>
</table>
<div class="cart-total">
<span>已选择 {{ checkedCount }} 件商品</span>
<span>总价:{{ totalPrice }}元</span>
</div>
<div class="cart-btn">
<button v-on:click="deleteAllItems">清空购物车</button>
<button v-on:click="submitOrder" :disabled="checkedCount === 0">结算</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash/lodash.min.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
// 购物车数据
cartData: [],
// 全选状态
allChecked: false
},
mounted() {
// 初始化购物车数据
this.cartData = JSON.parse(localStorage.getItem('cartData')) || [
{
id: 1,
name: '商品1',
price: 100,
count: 1,
imgUrl: 'https://picsum.photos/id/100/120/120',
checked: false
},
{
id: 2,
name: '商品2',
price: 200,
count: 1,
imgUrl: 'https://picsum.photos/id/200/120/120',
checked: false
},
{
id: 3,
name: '商品3',
price: 300,
count: 1,
imgUrl: 'https://picsum.photos/id/300/120/120',
checked: false
}
];
},
computed: {
// 计算已选中的商品数量
checkedCount() {
return this.cartData.filter(item => item.checked).length;
},
// 计算总价
totalPrice() {
return this.cartData.reduce((total, item) => {
if (item.checked) {
total += item.price * item.count;
}
return total;
}, 0);
}
},
methods: {
// 删除某个商品
deleteItem(index) {
this.cartData.splice(index, 1);
},
// 修改商品数量
changeCount(index, step) {
const item = this.cartData[index];
item.count += step;
if (item.count <= 0) {
item.count = 1;
}
},
// 清空购物车
deleteAllItems() {
this.cartData = [];
},
// 删除选中的商品
deleteAllCheckeds() {
_.remove(this.cartData, item => item.checked);
},
// 提交订单
submitOrder() {
alert('结算成功');
}
},
watch: {
// 监听cartData变化,并将其保存到本地存储
cartData: {
handler: function(newValue) {
localStorage.setItem('cartData', JSON.stringify(newValue));
},
deep: true
}
}
});
</script>
思考:什么时候可以发送初始化渲染请求?(越早越好)什么时候可以开始操作dom?(至少dom得渲染出来)
Vue生命周期:就是一个Vue实例从创建 到 销毁 的整个过程。
生命周期四个阶段:① 创建 ② 挂载 ③ 更新 ④ 销毁
1.创建阶段:创建响应式数据
2.挂载阶段:渲染模板
3.更新阶段:修改数据,更新视图
4.销毁阶段:销毁Vue实例
Vue生命周期过程中,会自动运行一些函数,被称为【生命周期钩子】→ 让开发者可以在【特定阶段】运行自己的代码
<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.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
count: 100,
title: '计数器'
},
// 1. 创建阶段(准备数据)
beforeCreate() {
console.log('beforeCreate');
},
// 2. 挂载阶段(渲染模板)
mounted() {
console.log('mounted');
},
// 3. 更新阶段(修改数据 → 更新视图)
beforeUpdate() {
console.log('beforeUpdate');
},
updated() {
console.log('updated');
},
// 4. 卸载阶段
beforeDestroy() {
console.log('beforeDestroy');
}
})
</script>
<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>
<div id="app">
<ul>
<li class="news">
<div class="left">
<div class="title">5G商用在即,三大运营商营收持续下降</div>
<div class="info">
<span>新京报经济新闻</span>
<span>2222-10-28 11:50:28</span>
</div>
</div>
<div class="right">
<img src="http://ajax-api.itheima.net/public/images/0.webp" alt="">
</div>
</li>
<li class="news">
<div class="left">
<div class="title">5G商用在即,三大运营商营收持续下降</div>
<div class="info">
<span>新京报经济新闻</span>
<span>2222-10-28 11:50:28</span>
</div>
</div>
<div class="right">
<img src="http://ajax-api.itheima.net/public/images/0.webp" alt="">
</div>
</li>
<li class="news">
<div class="left">
<div class="title">5G商用在即,三大运营商营收持续下降</div>
<div class="info">
<span>新京报经济新闻</span>
<span>2222-10-28 11:50:28</span>
</div>
</div>
<div class="right">
<img src="http://ajax-api.itheima.net/public/images/0.webp" alt="">
</div>
</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 接口地址:http://hmajax.itheima.net/api/news
// 请求方式:get
const app = new Vue({
el: '#app',
data: {
list: []
},
created() {
axios.get('http://hmajax.itheima.net/api/news')
.then(response => {
this.list = response.data;
})
.catch(error => {
console.log(error);
});
}
});
</script>
一般情况下,发起网络请求通常在Vue实例的mounted生命周期钩子中进行。mounted钩子会在Vue实例挂载到DOM后调用,此时可以执行异步操作,如发送网络请求获取数据。 以下是一个示例代码:
<script>
const app = new Vue({
el: '#app',
data: {
list: []
},
mounted() {
axios.get('http://hmajax.itheima.net/api/news')
.then(response => {
this.list = response.data;
})
.catch(error => {
console.log(error);
});
}
});
</script>
在created钩子中发起网络请求时,可以在Vue实例被创建后立即获取数据,并进行一些初始化的操作。但需要注意的是,在此时DOM元素尚未挂载到页面上,如果需要进行DOM操作,则可能会出现获取不到DOM元素的问题。 在mounted钩子中发起网络请求时,可以保证Vue实例已经被完全挂载到页面上,可以执行DOM操作,并且能够确保数据的准确性和可靠性。因此,一般情况下,在mounted钩子中发起网络请求更为普遍。
在HTML部分,我添加了一个 ref 属性在 元素上,并将其命名为 “inputElement”。这样,可以通过 this.
refs.inputElement 获取到输入框元素,并使用 .focus() 方法使其获得焦点,即自动聚焦到输入框。
<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;
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>
<div class="container" id="app">
<div class="search-container">
<img src="https://www.itheima.com/images/logo.png" alt="">
<div class="search-box">
<input type="text" v-model="words" ref="inputElement"><!-- 在 input 元素上添加 ref 属性 -->
<button @click="search">搜索一下</button><!-- 点击按钮时触发 search 函数 -->
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
words: ''
},
mounted() {
this.$refs.inputElement.focus(); // 在 mounted 阶段获取焦点
},
methods: {
search() {
// 执行搜索操作
console.log('搜索关键词:', this.words);
}
}
})
</script>
1.基本渲染
2.添加功能
3.删除功能
4.饼图渲染
1.基本渲染
2.添加功能
3.删除功能
4.饼图渲染
<!-- CSS only -->
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/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>
<div id="app">
<div class="contain">
<!-- 左侧列表 -->
<div class="list-box">
<!-- 添加资产 -->
<form class="my-form">
<input type="text" class="form-control" placeholder="消费名称" v-model="newExpense.name" />
<input type="text" class="form-control" placeholder="消费价格" v-model.number="newExpense.price" />
<button type="button" class="btn btn-primary" @click="addExpense">添加账单</button>
</form>
<table class="table table-hover">
<thead>
<tr>
<th>编号</th>
<th>消费名称</th>
<th>消费价格</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(expense, index) in expenses" :key="expense.id">
<td>{{ index + 1 }}</td>
<td>{{ expense.name }}</td>
<td :class="{ 'red': expense.price > 100 }">{{ expense.price }}</td>
<td><a href="javascript:;" @click="deleteExpense(expense.id)">删除</a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4">消费总计: {{ totalExpense }}</td>
</tr>
</tfoot>
</table>
</div>
<!-- 右侧图表 -->
<div class="echarts-box" id="main"></div>
</div>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
expenses: [], // 存储消费数据
newExpense: { name: '', price: 0 }, // 新增消费表单数据
chart: null, // echarts实例
},
computed: {
totalExpense() {
// 计算消费总额
return this.expenses.reduce((total, expense) => total + expense.price, 0);
}
},
methods: {
getExpenses() {
// 发送请求获取消费数据
axios.get('/api/expenses')
.then(response => {
this.expenses = response.data;
this.renderChart();
})
.catch(error => {
console.log(error);
});
},
addExpense() {
// 添加消费
if (this.newExpense.name !== '' && this.newExpense.price > 0) {
axios.post('/api/expenses', this.newExpense)
.then(response => {
this.newExpense.name = '';
this.newExpense.price = 0;
this.getExpenses(); // 重新获取消费数据并渲染
})
.catch(error => {
console.log(error);
});
}
},
deleteExpense(id) {
// 删除消费
axios.delete(`/api/expenses/${id}`)
.then(response => {
this.getExpenses(); // 重新获取消费数据并渲染
})
.catch(error => {
console.log(error);
});
},
renderChart() {
// 渲染图表
if (this.chart === null) {
// 初始化echarts实例
this.chart = echarts.init(document.getElementById('main'));
}
const option = {
// 配置图表选项
series: [
{
name: '消费统计',
type: 'pie',
data: this.expenses.map(expense => ({
name: expense.name,
value: expense.price
}))
}
]
};
// 更新图表
this.chart.setOption(option);
}
},
mounted() {
// 页面加载时获取消费数据并渲染
this.getExpenses();
}
});
</script>
工程化开发模式优点:
提高编码效率,比如使用JS新语法、Less/Sass、Typescript等通过webpack都可以编译成浏览器识别的ES3/ES5/CSS等
工程化开发模式问题:
为了解决以上问题,所以我们需要一个工具,生成标准化的配置
Vue CLI 是Vue官方提供的一个全局命令工具
可以帮助我们快速创建一个开发Vue项目的标准化基础架子。【集成了webpack配置】
虽然脚手架中的文件有很多,目前咱们只需认识三个文件即可
组件化:一个页面可以拆分成一个个组件,每个组件有着自己独立的结构、样式、行为。
好处:便于维护,利于复用 → 提升开发效率。
组件分类:普通组件、根组件。
比如:下面这个页面,可以把所有的代码都写在一个页面中,但是这样显得代码比较混乱,难易维护。咱们可以按模块进行组件划分
整个应用最上层的组件,包裹所有普通小组件
只能在注册的组件内使用
当成html标签使用即可 <组件名></组件名>
组件名规范 —> 大驼峰命名法, 如 HmHeader
// 导入需要注册的组件
import 组件对象 from '.vue文件路径'
import HmHeader from './components/HmHeader'
export default { // 局部注册
components: {
'组件名': 组件对象,
HmHeader:HmHeaer,
HmHeader
}
}
在App组件中,完成以下练习。在App.vue中使用组件的方式完成下面布局
<template>
<div class="hm-header">
我是hm-header
</div>
</template>
<script>
export default {
}
</script>
<style>
.hm-header {
height: 100px;
line-height: 100px;
text-align: center;
font-size: 30px;
background-color: #8064a2;
color: white;
}
</style>
<template>
<div class="hm-main">
我是hm-main
</div>
</template>
<script>
export default {
}
</script>
<style>
.hm-main {
height: 400px;
line-height: 400px;
text-align: center;
font-size: 30px;
background-color: #f79646;
color: white;
margin: 20px 0;
}
</style>
<template>
<div class="hm-footer">
我是hm-footer
</div>
</template>
<script>
export default {
}
</script>
<style>
.hm-footer {
height: 100px;
line-height: 100px;
text-align: center;
font-size: 30px;
background-color: #4f81bd;
color: white;
}
</style>
App.vue
<template>
<div class="app">
<header>
<hm-header/>
</header>
<main>
<hm-main/>
</main>
<footer>
<hm-footer/>
</footer>
</div>
</template>
<script>
import HmHeader from './HmHeader.vue';
import HmMain from './HmMain.vue';
import HmFooter from './HmFooter.vue';
export default {
name: 'App',
components: { HmHeader, HmMain, HmFooter }
}
</script>
<style>
.app {
display: flex;
flex-direction: column;
height: 100vh;
}
header {
flex-shrink: 0;
}
main {
flex-grow: 1;
}
footer {
flex-shrink: 0;
}
</style>
全局注册的组件,在项目的任何组件中都能使用
当成HTML标签直接使用
<组件名></组件名>
组件名规范 —> 大驼峰命名法, 如 HmHeader
Vue.component(‘组件名’, 组件对象)
例:
// 导入需要全局注册的组件
import HmButton from './components/HmButton'
Vue.component('HmButton', HmButton)
在以下3个局部组件中是展示一个通用按钮
<template>
<button class="hm-button">通用按钮</button>
</template>
<script>
export default {
}
</script>
<style>
.hm-button {
height: 50px;
line-height: 50px;
padding: 0 20px;
background-color: #3bae56;
border-radius: 5px;
color: white;
border: none;
vertical-align: middle;
cursor: pointer;
}
</style>
写在组件中的样式会 全局生效 → 因此很容易造成多个组件之间的样式冲突问题。
BaseOne.vue
<template>
<div class="base-one">
BaseOne
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
BaseTwo.vue
<template>
<div class="base-one">
BaseTwo
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
App.vue
<template>
<div id="app">
<BaseOne></BaseOne>
<BaseTwo></BaseTwo>
</div>
</template>
<script>
import BaseOne from './components/BaseOne'
import BaseTwo from './components/BaseTwo'
export default {
name: 'App',
components: {
BaseOne,
BaseTwo
}
}
</script>
最终效果: 必须是当前组件的元素, 才会有这个自定义属性, 才会被这个样式作用到
一个组件的 data 选项必须是一个函数。目的是为了:保证每个组件实例,维护独立的一份数据对象。
每次创建新的组件实例,都会新执行一次data 函数,得到一个新对象。
BaseCount.vue
<template>
<div class="base-count">
<button @click="count--">-</button>
<span>{{ count }}</span>
<button @click="count++">+</button>
</div>
</template>
<script>
export default {
data: function () {
return {
count: 100,
}
},
}
</script>
<style>
.base-count {
margin: 20px;
}
</style>
App.vue
<template>
<div class="app">
<BaseCount></BaseCount>
</div>
</template>
<script>
import BaseCount from './components/BaseCount'
export default {
components: {
BaseCount,
},
}
</script>
<style>
</style>
组件通信,就是指组件与组件之间的数据传递
思考:
父向子传值步骤
子组件利用 $emit 通知父组件,进行修改更新
子向父传值步骤
组件上 注册的一些 自定义属性
向子组件传递数据
组件的props可以乱传吗
为组件的 prop 指定验证要求,不符合要求,控制台就会有错误提示 → 帮助开发者,快速发现错误
App.vue
<template>
<div class="app">
<BaseProgress :w="width"></BaseProgress>
</div>
</template>
<script>
import BaseProgress from './components/BaseProgress.vue'
export default {
data() {
return {
width: 30,
}
},
components: {
BaseProgress,
},
}
</script>
<style>
</style>
BaseProgress.vue
<template>
<div class="base-progress">
<div class="inner" :style="{ width: w + '%' }">
<span>{{ w }}%</span>
</div>
</div>
</template>
<script>
export default {
props: {
w: {
type: Number,
required: true
}
}
}
</script>
<style scoped>
.base-progress {
height: 26px;
width: 400px;
border-radius: 15px;
background-color: #272425;
border: 3px solid #272425;
box-sizing: border-box;
margin-bottom: 30px;
}
.inner {
position: relative;
background: #379bff;
border-radius: 15px;
height: 25px;
box-sizing: border-box;
left: -3px;
top: -2px;
}
.inner span {
position: absolute;
right: 0;
top: 26px;
}
</style>
props: {
校验的属性名: {
type: 类型, // Number String Boolean ...
required: true, // 是否必填
default: 默认值, // 默认值
validator (value) {
// 自定义校验逻辑
return 是否通过校验
}
}
},
<script>
export default {
// 完整写法(类型、默认值、非空、自定义校验)
props: {
w: {
type: Number,
//required: true,
default: 0,
validator(val) {
// console.log(val)
if (val >= 100 || val <= 0) {
console.error('传入的范围必须是0-100之间')
return false
} else {
return true
}
},
},
},
}
</script>
1.default和required一般不同时写(因为当时必填项时,肯定是有值的)
2.default后面如果是简单类型的值,可以直接写默认。如果是复杂类型的值,则需要以函数的形式return一个默认值
都可以给组件提供数据
父级props 的数据更新,会向下流动,影响子组件。这个数据流动是单向的
可以将父组件传递的数据作为 props 属性传递给子组件,并在子组件内部通过触发事件来通知父组件修改数据。
BaseCount.vue
<template>
<div class="base-count">
<button @click="decrement">-</button>
<span>{{ count }}</span>
<button @click="increment">+</button>
</div>
</template>
<script>
export default {
props: {
count: {
type: Number,
required: true
}
},
methods: {
decrement() {
// 在子组件内部通过 $emit 触发一个自定义事件,通知父组件减少 count
this.$emit('decrement')
},
increment() {
// 在子组件内部通过 $emit 触发一个自定义事件,通知父组件增加 count
this.$emit('increment')
}
}
}
</script>
<style>
.base-count {
margin: 20px;
}
</style>
我们定义了两个按钮,分别触发 decrement 和 increment 方法。当点击按钮时,通过 $emit 方法触发一个自定义事件,通知父组件进行相应的操作
接下来,在父组件中,需要绑定子组件的 count 属性,并监听子组件的自定义事件,执行相应的操作:
App.vue
<template>
<div class="app">
<BaseCount :count="count" @decrement="decrementCount" @increment="incrementCount"></BaseCount>
</div>
</template>
<script>
import BaseCount from './components/BaseCount.vue'
export default {
data() {
return {
count: 100,
}
},
methods: {
decrementCount() {
this.count--
},
incrementCount() {
this.count++
}
},
components: {
BaseCount,
},
}
</script>
<style>
</style>
谁的数据谁负责
咱们可以把小黑记事本原有的结构拆成三部分内容:
思路分析:
思路分析:
思路分析:
思路分析:
<template>
<div class="app">
<todo-header @add-todo="addTodoItem"></todo-header>
<todo-main :todos="todos" @delete-todo="deleteTodoItem"></todo-main>
<todo-footer :todos="todos" @clear-todos="clearAll"></todo-footer>
</div>
</template>
<script>
import TodoHeader from './components/TodoHeader.vue';
import TodoMain from './components/TodoMain.vue';
import TodoFooter from './components/TodoFooter.vue';
export default {
components: {
TodoHeader,
TodoMain,
TodoFooter,
},
data() {
return {
todos: JSON.parse(localStorage.getItem('todos') || '[]'),
};
},
methods: {
addTodoItem(newTodoItem) {
this.todos.unshift({
id: Date.now(),
content: newTodoItem,
completed: false,
});
},
deleteTodoItem(todoId) {
this.todos = this.todos.filter((item) => item.id !== todoId);
},
clearAll() {
if (this.todos.length === 0) return;
this.todos = [];
},
},
watch: {
todos: {
handler(newTodos) {
localStorage.setItem('todos', JSON.stringify(newTodos));
},
deep: true,
},
},
};
</script>
<style scoped>
/* 样式省略 */
</style>
将整个应用拆分成了三个基础组件:头部组件(TodoHeader)、主体列表组件(TodoMain)和底部组件(TodoFooter)。
在父组件 App.vue 中,通过引入这三个子组件,并将数据和事件传递给它们来实现完整的应用。
同时,在父组件 App.vue 中定义了 todos 数组存储所有待办任务,通过 localStorage 实现了数据持久化存储。
在添加任务、删除任务及清空所有任务时,都会修改 todos 数组,从而触发 watch 监听函数将数据持久化到本地存储中。
下面是 TodoHeader、TodoMain 和 TodoFooter 组件的代码:
<template>
<div class="todo-header">
<input type="text" class="todo-input" placeholder="请输入任务" v-model="newTodoItem" @keyup.enter="addTodo"/>
<button class="add-btn" @click="addTodo">添加</button>
</div>
</template>
<script>
export default {
data() {
return {
newTodoItem: '',
}
},
methods: {
addTodo() {
if (!this.newTodoItem.trim()) return;
this.$emit('add-todo', this.newTodoItem);
this.newTodoItem = '';
}
}
}
</script>
<style scoped>
/* 样式省略 */
</style>
实现了输入框和添加按钮,并通过 v-model 双向绑定 newTodoItem 数据。当用户在输入框内敲击回车或者点击添加按钮时,会触发 addTodo 方法,并将 newTodoItem 的值传递给父组件。
<template>
<div class="todo-main">
<ul class="todo-list">
<li v-for="todo in todos" :key="todo.id">
<input type="checkbox" class="todo-checkbox" v-model="todo.completed">
<label class="todo-label" :class="{ 'completed': todo.completed }">{{ todo.content }}</label>
<span class="delete-btn" @click="deleteTodoItem(todo.id)">删除</span>
</li>
</ul>
</div>
</template>
<script>
export default {
props: {
todos: {
type: Array,
required: true,
}
},
methods: {
deleteTodoItem(todoId) {
this.$emit('delete-todo', todoId);
}
}
}
</script>
<style scoped>
/* 样式省略 */
</style>
通过 v-for 指令渲染了所有任务列表,并提供了勾选完成、任务内容和删除功能。当用户点击删除按钮时,会触发 deleteTodoItem 方法,并将对应任务的 id 传递给父组件。
<template>
<div class="todo-footer">
<span class="total-count">总任务数:{{ todos.length }}</span>
<button class="clear-btn" @click="clearAll">清空</button>
</div>
</template>
<script>
export default {
props: {
todos: {
type: Array,
required: true,
},
},
methods: {
clearAll() {
this.$emit('clear-todos');
}
},
}
</script>
<style scoped>
/* 样式省略 */
</style>
展示了当前所有待办任务的总数,并提供了清空所有任务的按钮。当用户点击清空按钮时,会触发 clearAll 方法,并通过自定义事件将信息通知给父组件。
非父子组件之间,进行简易消息传递。(复杂场景→ Vuex)
import Vue from 'vue'
const Bus = new Vue()
export default Bus
created () {
Bus.$on('sendMsg', (msg) => {
this.msg = msg
})
}
Bus.$emit('sendMsg', '这是一个消息')
EventBus.js
import Vue from 'vue'
const Bus = new Vue()
export default Bus
BaseA.vue(接受方)
<template>
<div class="base-a">
我是A组件(接收方)
<p>{{ msg }}</p>
</div>
</template>
<script>
import Bus from '../utils/EventBus'
export default {
data() {
return {
msg: '',
}
},
created() {
Bus.$on('message', (msg) => this.receiveMessage(msg))
},
methods: {
receiveMessage(msg) {
this.msg = msg
},
},
}
</script>
<style scoped>
.base-a {
width: 200px;
height: 200px;
border: 3px solid #000;
border-radius: 3px;
margin: 10px;
}
</style>
BaseB.vue(发送方)
<template>
<div class="base-b">
<div>我是B组件(发布方)</div>
<button @click="sendMessage">发送消息</button>
</div>
</template>
<script>
import Bus from '../utils/EventBus'
export default {
methods: {
sendMessage() {
Bus.$emit('message', 'Hello, BaseA!') // 发送消息
},
},
}
</script>
<style scoped>
.base-b {
width: 200px;
height: 200px;
border: 3px solid #000;
border-radius: 3px;
margin: 10px;
}
</style>
App.vue
<template>
<div class="app">
<BaseA></BaseA>
<BaseB></BaseB>
</div>
</template>
<script>
import BaseA from './components/BaseA.vue'
import BaseB from './components/BaseB.vue'
export default {
components:{
BaseA,
BaseB
}
}
</script>
<style>
</style>
跨层级共享数据
export default {
provide () {
return {
// 普通类型【非响应式】
color: this.color,
// 复杂类型【响应式】
userInfo: this.userInfo,
}
}
}
2.子/孙组件 inject获取数据
export default {
inject: ['color','userInfo'],
created () {
console.log(this.color, this.userInfo)
}
}
v-model本质上是一个语法糖。例如应用在输入框上,就是value属性 和 input事件 的合写
<template>
<div id="app" >
<input v-model="msg" type="text">
<input :value="msg" @input="msg = $event.target.value" type="text">
</div>
</template>
提供数据的双向绑定
$event 用于在模板中,获取事件的形参
<template>
<div class="app">
<input type="text" v-model="msg1" />
<br />
<input type="text" v-model="msg2" />
</div>
</template>
<script>
export default {
data() {
return {
msg1: '',
msg2: '',
}
},
}
</script>
<style>
</style>
通过在 input 元素上使用 v-model,可以将 msg1 和 msg2 双向绑定到输入框的值上。当输入框的值发生变化时,msg1 和 msg2 的值也会相应地更新。这样可以方便地实现数据的双向绑定,减少了手动监听和更新输入框的操作。
不同的表单元素, v-model在底层的处理机制是不一样的。比如给checkbox使用v-model
底层处理的是 checked属性和change事件。
不过咱们只需要掌握应用在文本框上的原理即可
实现子组件和父组件数据的双向绑定 (实现App.vue中的selectId和子组件选中的数据进行双向绑定)
App.vue
为了实现子组件和父组件数据的双向绑定,可以在 BaseSelect 组件中使用 v-model 语法糖来绑定 select 元素的值,然后通过 props 和 $emit 来进行父子组件间的通信。
在 App.vue 中,通过 v-model 将 BaseSelect 组件的值绑定到 selectId 上,并使用计算属性 selectedCity 来获取当前选择的城市名称。
<template>
<div class="app">
<BaseSelect v-model="selectId"></BaseSelect>
<p>当前选择的城市为:{{ selectedCity }}</p>
</div>
</template>
<script>
import BaseSelect from './components/BaseSelect.vue';
export default {
data() {
return {
selectId: '102',
cityOptions: [
{ value: '101', label: '北京' },
{ value: '102', label: '上海' },
{ value: '103', label: '武汉' },
{ value: '104', label: '广州' },
{ value: '105', label: '深圳' },
],
};
},
computed: {
selectedCity() {
const option = this.cityOptions.find(
(item) => item.value === this.selectId
);
return option ? option.label : '';
},
},
components: {
BaseSelect,
},
};
</script>
<style>
</style>
BaseSelect.vue
<template>
<div>
<select v-model="selected">
<option
:value="option.value"
v-for="(option, index) in options"
:key="index"
>
{{ option.label }}
</option>
</select>
</div>
</template>
<script>
export default {
props: {
value: String,
options: {
type: Array,
default: () => [],
},
},
computed: {
selected: {
get() {
return this.value;
},
set(val) {
this.$emit("input", val);
},
},
},
};
</script>
<style>
</style>
父组件通过v-model 简化代码,实现子组件和父组件数据 双向绑定
v-model其实就是 :value和@input事件的简写
当使用v-model简化代码时,可以通过以下步骤实现子组件和父组件的数据双向绑定。
<template>
<input type="text" :value="value" @input="$emit('input', $event.target.value)" />
</template>
<script>
export default {
props: {
value: String // 通过props接收父组件传递的value值
}
}
</script>
<template>
<div>
<ChildComponent v-model="data" />
<p>当前数值:{{ data }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
data() {
return {
data: '' // 初始化数据
}
}
}
</script>
在上面的例子中,我们创建了一个名为ChildComponent的子组件,在该组件中使用输入框展示和修改数据。通过props接收父组件传递的value值,并在输入框的value属性中绑定该值。通过@input事件触发子组件的input事件,将输入框的值传递给父组件。
在父组件中,我们使用ChildComponent组件,并通过v-model绑定数据。通过v-model,我们可以直接在父组件中双向绑定data属性,无需手动监听和更新。当子组件触发input事件时,父组件的data值会自动更新,反之亦然。
这样就通过v-model简化了代码,并实现了子组件和父组件数据的双向绑定。
可以实现 子组件 与 父组件数据 的 双向绑定,简化代码
简单理解:子组件可以修改父组件传过来的props值
封装弹框类的基础组件, visible属性 true显示 false隐藏
.sync修饰符 就是 :属性名 和 @update:属性名 合写
父组件
//.sync写法
<BaseDialog :visible.sync="isShow" />
--------------------------------------
//完整写法
<BaseDialog
:visible="isShow"
@update:visible="isShow = $event"
/>
子组件
props: {
visible: Boolean
},
this.$emit('update:visible', false)
App.vue
<template>
<div class="app">
<button @click="openDialog">退出按钮</button>
<BaseDialog :isShow.sync="isShow"></BaseDialog>
</div>
</template>
<script>
import BaseDialog from './components/BaseDialog.vue'
export default {
data() {
return {
isShow: false,
}
},
components: {
BaseDialog,
},
methods: {
openDialog() {
this.isShow = true;
}
}
}
</script>
<style>
</style>
BaseDialog.vue
<template>
<div class="base-dialog-wrap" v-show="visible">
<div class="base-dialog">
<div class="title">
<h3>温馨提示:</h3>
<button class="close" @click="closeDialog">x</button>
</div>
<div class="content">
<p>你确认要退出本系统么?</p>
</div>
<div class="footer">
<button @click="confirm">确认</button>
<button @click="closeDialog">取消</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
visible: Boolean,
},
methods: {
closeDialog() {
this.$emit('update:visible', false);
},
confirm() {
// 执行确认操作
// ...
this.closeDialog();
}
}
}
</script>
<style scoped>
.base-dialog-wrap {
width: 300px;
height: 200px;
box-shadow: 2px 2px 2px 2px #ccc;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
padding: 0 10px;
}
.base-dialog .title {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 2px solid #000;
}
.base-dialog .content {
margin-top: 38px;
}
.base-dialog .title .close {
width: 20px;
height: 20px;
cursor: pointer;
line-height: 10px;
}
.footer {
display: flex;
justify-content: flex-end;
margin-top: 26px;
}
.footer button {
width: 80px;
height: 40px;
}
.footer button:nth-child(1) {
margin-right: 10px;
cursor: pointer;
}
</style>
利用ref 和 $refs 可以用于 获取 dom 元素 或 组件实例
查找范围 → 当前组件内(更精确稳定)
1.给要获取的盒子添加ref属性
<div ref="chartRef">我是渲染图表的容器</div>
2.获取时通过
refs.chartRef 获取
mounted () {
console.log(this.$refs.chartRef)
}
之前只用document.querySelect(‘.box’) 获取的是整个页面中的盒子
App.vue
<template>
<div class="app">
<button @click="toggleChart">切换图表显示</button>
<BaseChart ref="chartRef"></BaseChart>
</div>
</template>
<script>
import BaseChart from './components/BaseChart.vue'
export default {
components: {
BaseChart
},
methods: {
toggleChart() {
this.$refs.chartRef.toggleChart();
}
}
}
</script>
<style>
</style>
BaseChart.vue
<template>
<div class="base-chart-box" ref="baseChartBox"></div>
</template>
<script>
// yarn add echarts 或者 npm i echarts
import * as echarts from 'echarts'
export default {
mounted() {
this.renderChart();
},
methods: {
renderChart() {
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(this.$refs.baseChartBox)
// 绘制图表
myChart.setOption({
title: {
text: 'ECharts 入门示例',
},
tooltip: {},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'],
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20],
},
],
})
},
toggleChart() {
var myChart = echarts.getInstanceByDom(this.$refs.baseChartBox);
myChart.setOption({
series: [
{
data: [Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10]
}
]
});
}
}
}
</script>
<style scoped>
.base-chart-box {
width: 400px;
height: 300px;
border: 3px solid #000;
border-radius: 6px;
}
</style>
在App.vue中添加了一个"切换图表显示"的按钮,并通过@click事件绑定toggleChart方法。该方法通过this.
refs.baseChartBox获取到dom元素,然后使用echarts初始化该dom,并绘制图表。同时,我们添加了toggleChart方法,用于切换图表数据的更新。通过echarts.getInstanceByDom(this.
refs获取到BaseChart组件的实例,并调用其中的方法来切换图表数据的显示。
编辑标题, 编辑框自动聚焦
<template>
<div class="app">
<div v-if="isShowEdit">
<input type="text" v-model="editValue" ref="inp" />
<button>确认</button>
</div>
<div v-else>
<span>{{ title }}</span>
<button @click="editFn">编辑</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
title: '大标题',
isShowEdit: false,
editValue: '',
}
},
methods: {
editFn() {
// 显示输入框
this.isShowEdit = true
// 获取焦点
this.$refs.inp.focus()
} },
}
</script>
“显示之后”,立刻获取焦点是不能成功的!
原因:Vue 是异步更新DOM (提升性能)
$nextTick:等 DOM更新后,才会触发执行此方法里的函数体
语法: this.$nextTick(函数体)
this.$nextTick(() => {
this.$refs.inp.focus()
})
注意:$nextTick 内的函数体 一定是箭头函数,这样才能让函数内部的this指向Vue实例
单页应用程序:SPA【Single Page Application】是指所有的功能都在一个html页面上实现
单页应用网站: 网易云音乐 https://music.163.com/
多页应用网站:京东 https://jd.com/
单页应用类网站:系统类网站 / 内部网站 / 文档类网站 / 移动端站点
多页应用类网站:公司官网 / 电商类网站
单页面应用程序,之所以开发效率高,性能好,用户体验好
最大的原因就是:页面按需更新
比如当点击【发现音乐】和【关注】时,只是更新下面部分内容,对于头部是不更新的
要按需更新,首先就需要明确:访问路径和 组件的对应关系!
访问路径 和 组件的对应关系如何确定呢? 路由
生活中的路由:设备和ip的映射关系
Vue中的路由:路径和组件的映射关系
认识插件 VueRouter,掌握 VueRouter 的基本使用步骤
修改地址栏路径时,切换显示匹配的组件
Vue 官方的一个路由插件,是一个第三方包
https://v3.router.vuejs.org/zh/
固定5个固定的步骤(不用死背,熟能生巧)
yarn add vue-router@3.6.5
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const router = new VueRouter()
new Vue({
render: h => h(App),
router:router
}).$mount('#app')
当我们配置完以上5步之后 就可以看到浏览器地址栏中的路由 变成了 /#/的形式。表示项目的路由已经被Vue-Router管理了
main.js
// 路由的使用步骤 5 + 2
// 5个基础步骤
// 1. 下载 v3.6.5
// yarn add vue-router@3.6.5
// 2. 引入
// 3. 安装注册 Vue.use(Vue插件)
// 4. 创建路由对象
// 5. 注入到new Vue中,建立关联
import VueRouter from 'vue-router'
Vue.use(VueRouter) // VueRouter插件初始化
const router = new VueRouter()
new Vue({
render: h => h(App),
router
}).$mount('#app')
App.vue
<div class="footer_wrap">
<a href="#/find">发现音乐</a>
<a href="#/my">我的音乐</a>
<a href="#/friend">朋友</a>
</div>
<div class="top">
<router-view></router-view>
</div>
注意: .vue文件 本质无区别
.vue文件分为2类,都是 .vue文件(本质无区别)
分类开来的目的就是为了 更易维护
问题:所有的路由配置都在main.js中合适吗?
目标:将路由模块抽离出来。 好处:拆分模块,利于维护
路径简写:
脚手架环境下 @指代src目录,可以用于快速引入组件
实现导航高亮效果
如果使用a标签进行跳转的话,需要给当前跳转的导航加样式,同时要移除上一个a标签的样式,太麻烦!!!
vue-router 提供了一个全局组件 router-link (取代 a 标签)
语法:
发现音乐
<div>
<div class="footer_wrap">
<router-link to="/find">发现音乐</router-link>
<router-link to="/my">我的音乐</router-link>
<router-link to="/friend">朋友</router-link>
</div>
<div class="top">
<!-- 路由出口 → 匹配的组件所展示的位置 -->
<router-view></router-view>
</div>
</div>
使用router-link跳转后,我们发现。当前点击的链接默认加了两个class的值 router-link-exact-active
和router-link-active
我们可以给任意一个class属性添加高亮样式即可实现功能
当我们使用跳转时,自动给当前导航加了两个类名
模糊匹配(用的多)
to=“/my” 可以匹配 /my /my/a /my/b …
只要是以/my开头的路径 都可以和 to="/my"匹配到
精确匹配
to=“/my” 仅可以匹配 /my
router-link的两个高亮类名 太长了,我们希望能定制怎么办
我们可以在创建路由对象时,额外配置两个配置项即可。 linkActiveClass
和linkExactActiveClass
const router = new VueRouter({
routes: [...],
linkActiveClass: "类名1",
linkExactActiveClass: "类名2"
})
// 创建了一个路由对象
const router = new VueRouter({
routes: [
...
],
linkActiveClass: 'active', // 配置模糊匹配的类名
linkExactActiveClass: 'exact-active' // 配置精确匹配的类名
})
在跳转路由时,进行传参
比如:现在我们在搜索页点击了热门搜索链接,跳转到详情页,需要把点击的内容带到详情页,改怎么办呢?
我们可以通过两种方式,在跳转的时候把所需要的参数传到其他页面中
App.vue
<template>
<div id="app">
<div class="link">
<router-link to="/home">首页</router-link>
<router-link to="/search">搜索页</router-link>
</div>
<router-view></router-view>
</div>
</template>
<script>
export default {};
</script>
<style scoped>
.link {
height: 50px;
line-height: 50px;
background-color: #495150;
display: flex;
margin: -8px -8px 0 -8px;
margin-bottom: 50px;
}
.link a {
display: block;
text-decoration: none;
background-color: #ad2a26;
width: 100px;
text-align: center;
margin-right: 5px;
color: #fff;
border-radius: 5px;
}
</style>
Home.vue
<template>
<div class="home">
<div class="logo-box"></div>
<div class="search-box">
<input type="text">
<button>搜索一下</button>
</div>
<div class="hot-link">
热门搜索:
<router-link :to="{ path: '/search', query: { keywords: '黑马程序员', type: 'video' } }">热门搜索1</router-link>
<router-link :to="{ path: '/search', query: { keywords: '前端培训', type: 'article' } }">热门搜索2</router-link>
<router-link :to="{ path: '/search', query: { keywords: '如何成为前端大牛', type: 'book' } }">热门搜索3</router-link>
</div>
</div>
</template>
<script>
export default {};
</script>
<style>
.logo-box {
height: 150px;
background: url('@/assets/logo.jpeg') no-repeat center;
}
.search-box {
display: flex;
justify-content: center;
}
.search-box input {
width: 400px;
height: 30px;
line-height: 30px;
border: 2px solid #c4c7ce;
border-radius: 4px 0 0 4px;
outline: none;
}
.search-box input:focus {
border: 2px solid #ad2a26;
}
.search-box button {
width: 100px;
height: 36px;
border: none;
background-color: #ad2a26;
color: #fff;
position: relative;
left: -2px;
border-radius: 0 4px 4px 0;
}
.hot-link {
width: 508px;
height: 60px;
line-height: 60px;
margin: 0 auto;
}
.hot-link a {
margin: 0 5px;
}
</style>
Search.vue
<template>
<div class="search">
<p>搜索关键字: {{ keywords }}</p>
<p>搜索类型: {{ type }}</p>
<p>搜索结果: </p>
<ul>
<li>.............</li>
<li>.............</li>
<li>.............</li>
<li>.............</li>
</ul>
</div>
</template>
<script>
export default {
name: 'Search',
data () {
return {
keywords: '',
type: ''
}
},
created () {
// 获取路由参数
this.keywords = this.$route.query.keywords || ''
this.type = this.$route.query.type || ''
}
}
</script>
<style>
.search {
width: 400px;
height: 240px;
padding: 0 20px;
margin: 0 auto;
border: 2px solid #c4c7ce;
border-radius: 5px;
}
</style>
router/index.js
import Home from '@/views/Home'
import Search from '@/views/Search'
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter) // VueRouter插件初始化
// 创建了一个路由对象
const router = new VueRouter({
routes: [
{ path: '/home', component: Home },
{ path: '/search', component: Search }
]
})
export default router
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router
}).$mount('#app')
动态路由后面的参数可以随便起名,但要有语义
params后面的参数名要和动态路由配置的参数保持一致
注意:动态路由也可以传多个参数,但一般只传一个
声明式导航跳转时, 有几种方式传值给路由页面?
配了路由 path:“/search/:words” 为什么按下面步骤操作,会未匹配到组件,显示空白?
/search/:words 表示,必须要传参数。如果不传参数,也希望匹配,可以加个可选符"?"
const router = new VueRouter({
routes: [
...
{ path: '/search/:words?', component: Search }
]
})
网页打开时, url 默认是 / 路径,未匹配到组件时,会出现空白
重定向 → 匹配 / 后, 强制跳转 /home 路径
{ path: 匹配路径, redirect: 重定向到的路径 },
比如:
{ path:'/' ,redirect:'/home' }
const router = new VueRouter({
routes: [
{ path: '/', redirect: '/home'},
...
]
})
当路径找不到匹配时,给个提示页面
404的路由,虽然配置在任何一个位置都可以,但一般都配置在其他路由规则的最后面
path: “*” (任意路径) – 前面不匹配就命中最后这个
import NotFind from '@/views/NotFind'
const router = new VueRouter({
routes: [
...
{ path: '*', component: NotFind } //最后一个
]
})
NotFound.vue
<template>
<div>
<h1>404 Not Found</h1>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
router/index.js
...
import NotFound from '@/views/NotFound'
...
// 创建了一个路由对象
const router = new VueRouter({
routes: [
...
{ path: '*', component: NotFound }
]
})
export default router
路由的路径看起来不自然, 有#,能否切成真正路径形式?
const router = new VueRouter({
mode:'histroy', //默认是hash
routes:[]
})
点击按钮跳转如何实现?
编程式导航:用JS代码来进行跳转
两种语法:
特点:简易方便
//简单写法
this.$router.push('路由路径')
//完整写法
this.$router.push({
path: '路由路径'
})
特点:适合 path 路径长的场景
语法:
{ name: '路由名', path: '/path/xxx', component: XXX },
this.$router.push({
name: '路由名'
})
点击搜索按钮,跳转需要把文本框中输入的内容传到下一个页面如何实现?
1.查询参数
2.动态路由传参
两种跳转方式,对于两种传参方式都支持:
① path 路径跳转传参
② name 命名路由跳转传参
//简单写法
this.$router.push('/路径?参数名1=参数值1&参数2=参数值2')
//完整写法
this.$router.push({
path: '/路径',
query: {
参数名1: '参数值1',
参数名2: '参数值2'
}
})
接受参数的方式依然是:$route.query.参数名
//简单写法
this.$router.push('/路径/参数值')
//完整写法
this.$router.push({
path: '/路径/参数值'
})
接受参数的方式依然是:$route.params.参数值
**注意:**path不能配合params使用
this.$router.push({
name: '路由名字',
query: {
参数名1: '参数值1',
参数名2: '参数值2'
}
})
this.$router.push({
name: '路由名字',
params: {
参数名: '参数值',
}
})
编程式导航,如何跳转传参?
1.path路径跳转
this.$router.push('/路径?参数名1=参数值1&参数2=参数值2')
this.$router.push({
path: '/路径',
query: {
参数名1: '参数值1',
参数名2: '参数值2'
}
})
this.$router.push('/路径/参数值')
this.$router.push({
path: '/路径/参数值'
})
2.name命名路由跳转
this.$router.push({
name: '路由名字',
query: {
参数名1: '参数值1',
参数名2: '参数值2'
}
})
this.$router.push({
name: '路由名字',
params: {
参数名: '参数值',
}
})
1.配置路由
2.实现功能
1.把文档中准备的素材拷贝到项目中
2.针对router/index.js文件 进行一级路由配置
...
import Layout from '@/views/Layout.vue'
import ArticleDetail from '@/views/ArticleDetail.vue'
...
const router = new VueRouter({
routes: [
{
path: '/',
component: Layout
},
{
path: '/detail',
component: ArticleDetail
}
]
})
二级路由也叫嵌套路由,当然也可以嵌套三级、四级…
当在页面中点击链接跳转,只是部分内容切换时,我们可以使用嵌套路由
1.在一级路由下,配置children属性
注意:一级的路由path 需要加 /
二级路由的path不需要加 /
const router = new VueRouter({
routes: [
{
path: '/',
component: Layout,
children:[
//children中的配置项 跟一级路由中的配置项一模一样
{path:'xxxx',component:xxxx.vue},
{path:'xxxx',component:xxxx.vue},
]
}
]
})
技巧:二级路由应该配置到哪个一级路由下呢?
这些二级路由对应的组件渲染到哪个一级路由下,children就配置到哪个路由下边
2.配置二级路由的出口
注意: 配置了嵌套路由,一定配置对应的路由出口,否则不会渲染出对应的组件
Layout.vue
<template>
<div class="h5-wrapper">
<div class="content">
<router-view></router-view>
</div>
....
</div>
</template>
router/index.js
...
import Article from '@/views/Article.vue'
import Collect from '@/views/Collect.vue'
import Like from '@/views/Like.vue'
import User from '@/views/User.vue'
...
const router = new VueRouter({
routes: [
{
path: '/',
component: Layout,
redirect: '/article',
children:[
{
path:'/article',
component:Article
},
{
path:'/collect',
component:Collect
},
{
path:'/like',
component:Like
},
{
path:'/user',
component:User
}
]
},
....
]
})
Layout.vue
<template>
<div class="h5-wrapper">
<div class="content">
<!-- 内容部分 -->
<router-view></router-view>
</div>
<nav class="tabbar">
<a href="#/article">面经</a>
<a href="#/collect">收藏</a>
<a href="#/like">喜欢</a>
<a href="#/user">我的</a>
</nav>
</div>
</template>
Layout.vue
....
<nav class="tabbar">
<router-link to="/article">面经</router-link>
<router-link to="/collect">收藏</router-link>
<router-link to="/like">喜欢</router-link>
<router-link to="/user">我的</router-link>
</nav>
<style>
a.router-link-active {
color: orange;
}
</style>
1.安装axios
2.看接口文档,确认请求方式,请求地址,请求参数
3.created中发送请求,获取数据,存储到data中
4.页面动态渲染
1.安装axios
yarn add axios
npm i axios
2.接口文档
请求地址: https://mock.boxuegu.com/mock/3083/articles
请求方式: get
3.created中发送请求,获取数据,存储到data中
data() {
return {
articelList: [],
}
},
async created() {
const { data: { result: { rows } }} = await axios.get('https://mock.boxuegu.com/mock/3083/articles')
this.articelList = rows
},
4.页面动态渲染
<template>
<div class="article-page">
<div class="article-item" v-for="item in articelList" :key="item.id">
<div class="head">
<img :src="item.creatorAvatar" alt="" />
<div class="con">
<p class="title">{{ item.stem }}</p>
<p class="other">{{ item.creatorName }} | {{ item.createdAt }}</p>
</div>
</div>
<div class="body">
{{item.content}}
</div>
<div class="foot">点赞 {{item.likeCount}} | 浏览 {{item.views}}</div>
</div>
</div>
</template>
跳转详情页需要把当前点击的文章id传给详情页,获取数据
Article.vue
<template>
<div class="article-page">
<div class="article-item"
v-for="item in articelList" :key="item.id"
@click="$router.push(`/detail?id=${item.id}`)">
...
</div>
</div>
</template>
ArticleDetail.vue
created(){
console.log(this.$route.query.id)
}
改造路由
router/index.js
...
{
path: '/detail/:id',
component: ArticleDetail
}
Article.vue
<div class="article-item"
v-for="item in articelList" :key="item.id"
@click="$router.push(`/detail/${item.id}`)">
....
</div>
ArticleDetail.vue
created(){
console.log(this.$route.params.id)
}
ArticleDetail.vue
<template>
<div class="article-detail-page">
<nav class="nav"><span class="back" @click="$router.back()"><</span> 面经详情</nav>
....
</div>
</template>
接口文档
请求地址: https://mock.boxuegu.com/mock/3083/articles/:id
请求方式: get
在created中发送请求
data() {
return {
articleDetail:{}
}
},
async created() {
const id = this.$route.params.id
const {data:{result}} = await axios.get(
`https://mock.boxuegu.com/mock/3083/articles/${id}`
)
this.articleDetail = result
},
页面动态渲染
<template>
<div class="article-detail-page">
<nav class="nav">
<span class="back" @click="$router.back()"><</span> 面经详情
</nav>
<header class="header">
<h1>{{articleDetail.stem}}</h1>
<p>{{articleDetail.createAt}} | {{articleDetail.views}} 浏览量 | {{articleDetail.likeCount}} 点赞数</p>
<p>
<img
:src="articleDetail.creatorAvatar"
alt=""
/>
<span>{{articleDetail.creatorName}}</span>
</p>
</header>
<main class="body">
{{articleDetail.content}}
</main>
</div>
</template>
从面经列表 点到 详情页,又点返回,数据重新加载了 → 希望回到原来的位置
当路由被跳转后,原来所看到的组件就被销毁了(会执行组件内的beforeDestroy和destroyed生命周期钩子),重新返回后组件又被重新创建了(会执行组件内的beforeCreate,created,beforeMount,Mounted生命周期钩子),所以数据被加载了
利用keep-alive把原来的组件给缓存下来
keep-alive 是 Vue 的内置组件,当它包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。
keep-alive 是一个抽象组件:它自身不会渲染成一个 DOM 元素,也不会出现在父组件中。
优点:
在组件切换过程中把切换出去的组件保留在内存中,防止重复渲染DOM,
减少加载时间及性能消耗,提高用户体验性。
App.vue
<template>
<div class="h5-wrapper">
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
</template>
问题:
缓存了所有被切换的组件
① include : 组件名数组,只有匹配的组件会被缓存
② exclude : 组件名数组,任何匹配的组件都不会被缓存
③ max : 最多可以缓存多少组件实例
App.vue
<template>
<div class="h5-wrapper">
<keep-alive :include="['LayoutPage']">
<router-view></router-view>
</keep-alive>
</div>
</template>
keep-alive的使用会触发两个生命周期函数
activated 当组件被激活(使用)的时候触发 → 进入这个页面的时候触发
deactivated 当组件不被使用的时候触发 → 离开这个页面的时候触发
组件缓存后就不会执行组件的created, mounted, destroyed 等钩子了
所以其提供了actived 和deactived钩子,帮我们实现业务需求。
1.安装脚手架 (已安装)
npm i @vue/cli -g
2.创建项目
vue create hm-exp-mobile
Vue CLI v5.0.8
? Please pick a preset:
Default ([Vue 3] babel, eslint)
Default ([Vue 2] babel, eslint)
> Manually select features 选自定义
3.x
> 2.x
npm run serve
代码规范:一套写代码的约定规则。例如:赋值符号的左右是否需要空格?一句结束是否是要加;?…
没有规矩不成方圆
ESLint:是一个代码检查工具,用来检查你的代码是否符合指定的规则(你和你的团队可以自行约定一套规则)。在创建项目时,我们使用的是 JavaScript Standard Style 代码风格的规则。
建议把:https://standardjs.com/rules-zhcn.html 看一遍,然后在写的时候, 遇到错误就查询解决。
下面是这份规则中的一小部分:
if (condition) { ... }
function name (arg) { ... }
===
摒弃 ==
一但在需要检查 null || undefined
时可以使用 obj == null
如果你的代码不符合standard的要求,eslint会跳出来刀子嘴,豆腐心地提示你。
下面我们在main.js中随意做一些改动:添加一些空行,空格。
import Vue from 'vue'
import App from './App.vue'
import './styles/index.less'
import router from './router'
Vue.config.productionTip = false
new Vue ( {
render: h => h(App),
router
}).$mount('#app')
按下保存代码之后:
你将会看在控制台中输出如下错误:
eslint 是来帮助你的。心态要好,有错,就改。
根据错误提示来一项一项手动修正。
如果你不认识命令行中的语法报错是什么意思,你可以根据错误代码(func-call-spacing, space-in-parens,…)去 ESLint 规则列表中查找其具体含义。
打开 ESLint 规则表,使用页面搜索(Ctrl + F)这个代码,查找对该规则的一个释义。
// 当保存的时候,eslint自动帮我们修复错误
"editor.codeActionsOnSave": {
"source.fixAll": true
},
// 保存代码,不自动格式化
"editor.formatOnSave": false
settings.json 参考
{
"window.zoomLevel": 2,
"workbench.iconTheme": "vscode-icons",
"editor.tabSize": 2,
"emmet.triggerExpansionOnTab": true,
// 当保存的时候,eslint自动帮我们修复错误
"editor.codeActionsOnSave": {
"source.fixAll": true
},
// 保存代码,不自动格式化
"editor.formatOnSave": false
}
目标:明确Vuex是什么,应用场景以及优势
Vuex 是一个 Vue 的 状态管理工具,状态就是数据。
大白话:Vuex 是一个插件,可以帮我们管理 Vue 通用的数据 (多组件共享的数据)。例如:购物车数据 个人信息数
官方原文:
Vuex就像《近视眼镜》, 你自然会知道什么时候需要用它~
目标:基于脚手架创建项目,构建 vuex 多组件数据共享环境
效果是三个组件共享一份数据:
vue create vuex-demo
|-components
|--Son1.vue
|--Son2.vue
|-App.vue
App.vue
引入 Son1 和 Son2 这两个子组件,并添加共享的数据和对应的操作方法:
<template>
<div id="app">
<h1>根组件</h1>
<input type="text" v-model="sharedData">
<Son1 :sharedData="sharedData" :incrementData="incrementData"></Son1>
<hr>
<Son2 :sharedData="sharedData" :decrementData="decrementData"></Son2>
</div>
</template>
<script>
import Son1 from './components/Son1.vue'
import Son2 from './components/Son2.vue'
import { mapMutations } from 'vuex'
export default {
name: 'app',
data: function () {
return {
sharedData: ''
}
},
components: {
Son1,
Son2
},
methods: {
...mapMutations(['increment', 'decrement']),
incrementData() {
this.increment()
},
decrementData() {
this.decrement()
}
}
}
</script>
<style>
#app {
width: 600px;
margin: 20px auto;
border: 3px solid #ccc;
border-radius: 3px;
padding: 10px;
}
</style>
main.js
引入vuex并创建一个store来共享数据:
import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
Vue.config.productionTip = false
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
}
})
new Vue({
store,
render: h => h(App)
}).$mount('#app')
Son1.vue
接收父组件传递的共享数据,并对数据进行操作:
<!-- Son1.vue -->
<template>
<div class="box">
<h2>Son1 子组件</h2>
从vuex中获取的值: {{ sharedData }}
<br>
<button @click="incrementData">值 + 1</button>
</div>
</template>
<script>
export default {
name: 'Son1Com',
props: ['sharedData', 'incrementData']
}
</script>
<style lang="css" scoped>
.box{
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
</style>
Son2.vue
<!-- Son2.vue -->
<template>
<div class="box">
<h2>Son2 子组件</h2>
从vuex中获取的值: {{ sharedData }}
<br />
<button @click="decrementData">值 - 1</button>
</div>
</template>
<script>
export default {
name: 'Son2Com',
props: ['sharedData', 'decrementData']
}
</script>
<style lang="css" scoped>
.box {
border: 3px solid #ccc;
width: 400px;
padding: 10px;
margin: 20px;
}
h2 {
margin-top: 10px;
}
</style>
安装vuex与vue-router类似,vuex是一个独立存在的插件,如果脚手架初始化没有选 vuex,就需要额外安装。
yarn add vuex@3 或者 npm i vuex@3
store/index.js
专门存放 vuex为了维护项目目录的整洁,在src目录下新建一个store目录其下放置一个index.js文件。 (和 router/index.js
类似)

store/index.js
// 导入 vue
import Vue from 'vue'
// 导入 vuex
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)
// 创建仓库 store
const store = new Vuex.Store()
// 导出仓库
export default store
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store
}).$mount('#app')
此刻起, 就成功创建了一个 空仓库!!
App.vue
created(){
console.log(this.$store)
}
明确如何给仓库 提供 数据,如何 使用 仓库的数据
State提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储。
打开项目中的store.js文件,在state对象中可以添加我们要共享的数据。
// 创建仓库 store
const store = new Vuex.Store({
// state 状态, 即数据, 类似于vue组件中的data,
// 区别:
// 1.data 是组件自己的数据,
// 2.state 中的数据整个vue项目的组件都能访问到
state: {
count: 101
}
})
问题: 如何在组件中获取count?
获取 store:
1.Vue模板中获取 this.$store
2.js文件中获取 import 导入 store
模板中: {{ $store.state.xxx }}
组件逻辑中: this.$store.state.xxx
JS模块中: store.state.xxx
组件中可以使用 $store 获取到vuex中的store对象实例,可通过state属性属性获取count, 如下
<h1>state的数据 - {{ $store.state.count }}</h1>
将state属性定义在计算属性中 https://vuex.vuejs.org/zh/guide/state.html
<h1>state的数据 - {{ count }}</h1>
// 把state中数据,定义在组件内的计算属性中
computed: {
count () {
return this.$store.state.count
}
}
//main.js
import store from "@/store"
console.log(store.state.count)
每次都像这样一个个的提供计算属性, 太麻烦了,我们有没有简单的语法帮我们获取state中的值呢?
mapState是辅助函数,帮助我们把store中的数据映射到 组件的计算属性中, 它属于一种方便的用法
用法 :
import { mapState } from 'vuex'
mapState(['count'])
上面代码的最终得到的是 类似于
count () {
return this.$store.state.count
}
computed: {
...mapState(['count'])
}
<div> state的数据:{{ count }}</div>
明确 vuex 同样遵循单向数据流,组件中不能直接修改仓库的数据
Son1.vue
button @click="handleAdd">值 + 1</button>
methods:{
handleAdd (n) {
// 错误代码(vue默认不会监测,监测需要成本)
this.$store.state.count++
// console.log(this.$store.state.count)
},
}
通过 strict: true
可以开启严格模式,开启严格模式后,直接修改state中的值会报错
state数据的修改只能通过mutations,并且mutations必须是同步的
const store = new Vuex.Store({
state: {
count: 0
},
// 定义mutations
mutations: {
}
})
mutations是一个对象,对象中存放修改state的方法
mutations: {
// 方法里参数 第一个参数是当前store的state属性
// payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷
addCount (state) {
state.count += 1
}
},
this.$store.commit('addCount')
1.在mutations中定义个点击按钮进行 +5 的方法
// mutations
mutations: {
incrementByFive(state) {
state.count += 5;
}
}
2.在mutations中定义个点击按钮进行 改变title 的方法
// mutations
mutations: {
changeTitle(state, newTitle) {
state.title = newTitle;
}
}
3.在组件中调用mutations修改state中的值
<!-- App.vue -->
<template>
<div id="app">
<h1>{{ title }}</h1>
<button @click="incrementByFive">+5</button>
<button @click="changeTitle('New Title')">Change Title</button>
</div>
</template>
<script>
export default {
name: 'app',
computed: {
count() {
return this.$store.state.count;
},
title() {
return this.$store.state.title;
}
},
methods: {
incrementByFive() {
this.$store.commit('incrementByFive');
},
changeTitle(newTitle) {
this.$store.commit('changeTitle', newTitle);
}
}
}
</script>
通过mutations修改state的步骤
1.定义 mutations 对象,对象中存放修改 state 的方法
2.组件中提交调用 mutations(通过$store.commit(‘mutations的方法名’))
掌握 mutations 传参语法
看下面这个案例,每次点击不同的按钮,加的值都不同,每次都要定义不同的mutations处理吗?
提交 mutation 是可以传递参数的 this.$store.commit('xxx', 参数)
mutations: {
...
addCount (state, count) {
state.count = count
}
},
handle ( ) {
this.$store.commit('addCount', 10)
}
小tips: 提交的参数只能是一个, 如果有多个参数要传, 可以传递一个对象
this.$store.commit('addCount', {
count: 10
})
Son2.vue
<button @click="subCount(1)">值 - 1</button>
<button @click="subCount(5)">值 - 5</button>
<button @click="subCount(10)">值 - 10</button>
export default {
methods:{
subCount (n) {
this.$store.commit('addCount', n)
},
}
}
store/index.js
mutations:{
subCount (state, n) {
state.count -= n
},
}
实时输入,实时更新,巩固 mutations 传参语法
App.vue
<input :value="count" @input="handleInput" type="text">
export default {
methods: {
handleInput (e) {
// 1. 实时获取输入框的值
const num = +e.target.value
// 2. 提交mutation,调用mutation函数
this.$store.commit('changeCount', num)
}
}
}
store/index.js
mutations: {
changeCount (state, newCount) {
state.count = newCount
}
},
mapMutations和mapState很像,它把位于mutations中的方法提取了出来,我们可以将它导入
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['addCount'])
}
上面代码的含义是将mutations的方法导入了methods中,等价于
methods: {
// commit(方法名, 载荷参数)
addCount () {
this.$store.commit('addCount')
}
}
此时,就可以直接通过this.addCount调用了
<button @click="addCount">值+1</button>
但是请注意: Vuex中mutations中要求不能写异步代码,如果有异步的ajax请求,应该放置在actions中
state是存放数据的,mutations是同步更新数据 (便于监测数据的变化, 更新视图等, 方便于调试工具查看变化),
actions则负责进行异步操作
说明:mutations必须是同步的
需求: 一秒钟之后, 要给一个数 去修改state
mutations: {
changeCount (state, newCount) {
state.count = newCount
}
}
actions: {
setAsyncCount (context, num) {
// 一秒后, 给一个数, 去修改 num
setTimeout(() => {
context.commit('changeCount', num)
}, 1000)
}
},
setAsyncCount () {
this.$store.dispatch('setAsyncCount', 666)
}
1.目标:掌握辅助函数 mapActions,映射方法
mapActions 是把位于 actions中的方法提取了出来,映射到组件methods中
Son2.vue
import { mapActions } from 'vuex'
methods: {
...mapActions(['changeCountAction'])
}
//mapActions映射的代码 本质上是以下代码的写法
//methods: {
// changeCountAction (n) {
// this.$store.dispatch('changeCountAction', n)
// },
//}
直接通过 this.方法 就可以调用
<button @click="changeCountAction(200)">+异步</button>
除了state之外,有时我们还需要从state中筛选出符合条件的一些数据,这些数据是依赖state的,此时会用到getters
例如,state中定义了list,为1-10的数组,
state: {
list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
组件中,需要显示所有大于5的数据,正常的方式,是需要list在组件中进行再一步的处理,但是getters可以帮助我们实现它
getters: {
// getters函数的第一个参数是 state
// 必须要有返回值
filterList: state => state.list.filter(item => item > 5)
}
<div>{{ $store.getters.filterList }}</div>
computed: {
...mapGetters(['filterList'])
}
<div>{{ filterList }}</div>
掌握核心概念 module 模块的创建
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
这句话的意思是,如果把所有的状态都放在state中,当项目变得越来越大的时候,Vuex会变得越来越难以维护
由此,又有了Vuex的模块化
定义两个模块 user 和 setting
user中管理用户的信息状态 userInfo modules/user.js
const state = {
userInfo: {
name: 'zs',
age: 18
}
}
const mutations = {}
const actions = {}
const getters = {}
export default {
state,
mutations,
actions,
getters
}
setting中管理项目应用的 主题色 theme,描述 desc, modules/setting.js
const state = {
theme: 'dark'
desc: '描述真呀真不错'
}
const mutations = {}
const actions = {}
const getters = {}
export default {
state,
mutations,
actions,
getters
}
在store/index.js
文件中的modules配置项中,注册这两个模块
import user from './modules/user'
import setting from './modules/setting'
const store = new Vuex.Store({
modules:{
user,
setting
}
})
使用模块中的数据, 可以直接通过模块名访问 store.state.模块名.xxx =>
也可以通过 mapState 映射
掌握模块中 state 的访问语法
尽管已经分模块了,但其实子模块的状态,还是会挂到根级别的 state 中,属性名就是模块名
modules/user.js
const state = {
userInfo: {
name: 'zs',
age: 18
},
myMsg: '我的数据'
}
const mutations = {
updateMsg (state, msg) {
state.myMsg = msg
}
}
const actions = {}
const getters = {}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
$store直接访问
$store.state.user.userInfo.name
mapState辅助函数访问
...mapState('user', ['userInfo']),
...mapState('setting', ['theme', 'desc']),
掌握模块中 getters 的访问语
使用模块中 getters 中的数据:
$store.getters['模块名/xxx ']
mapGetters([ 'xxx' ])
mapGetters('模块名', ['xxx'])
- 需要开启命名空间modules/user.js
const getters = {
// 分模块后,state指代子模块的state
UpperCaseName (state) {
return state.userInfo.name.toUpperCase()
}
}
Son1.vue 直接访问getters
<!-- 测试访问模块中的getters - 原生 -->
<div>{{ $store.getters['user/UpperCaseName'] }}</div>
Son2.vue 通过命名空间访问
computed:{
...mapGetters('user', ['UpperCaseName'])
}
掌握模块中 mutation 的调用语法
默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间,才会挂载到子模块。
modules/user.js
const mutations = {
setUser (state, newUserInfo) {
state.userInfo = newUserInfo
}
}
modules/setting.js
const mutations = {
setTheme (state, newTheme) {
state.theme = newTheme
}
}
Son1.vue
<button @click="updateUser">更新个人信息</button>
<button @click="updateTheme">更新主题色</button>
export default {
methods: {
updateUser () {
// $store.commit('模块名/mutation名', 额外传参)
this.$store.commit('user/setUser', {
name: 'xiaowang',
age: 25
})
},
updateTheme () {
this.$store.commit('setting/setTheme', 'pink')
}
}
}
Son2.vue
<button @click="setUser({ name: 'xiaoli', age: 80 })">更新个人信息</button>
<button @click="setTheme('skyblue')">更新主题</button>
methods:{
// 分模块的映射
...mapMutations('setting', ['setTheme']),
...mapMutations('user', ['setUser']),
}
掌握模块中 action 的调用语法 (同理 - 直接类比 mutation 即可)
默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间,才会挂载到子模块。
需求:
modules/user.js
const actions = {
setUserSecond (context, newUserInfo) {
// 将异步在action中进行封装
setTimeout(() => {
// 调用mutation context上下文,默认提交的就是自己模块的action和mutation
context.commit('setUser', newUserInfo)
}, 1000)
}
}
Son1.vue 直接通过store调用
<button @click="updateUser2">一秒后更新信息</button>
methods:{
updateUser2 () {
// 调用action dispatch
this.$store.dispatch('user/setUserSecond', {
name: 'xiaohong',
age: 28
})
},
}
Son2.vue mapActions映射
<button @click="setUserSecond({ name: 'xiaoli', age: 80 })">一秒后更新信息</button>
methods:{
...mapActions('user', ['setUserSecond'])
}
1.import { mapXxxx, mapXxx } from ‘vuex’
computed、methods: {
// **...mapState、...mapGetters放computed中;**
// **...mapMutations、...mapActions放methods中;**
...mapXxxx(**'模块名'**, ['数据项|方法']),
...mapXxxx(**'模块名'**, { 新的名字: 原来的名字 }),
}
2.组件中直接使用 属性 {{ age }}
或 方法 @click="updateAge(2)"
vue create vue-cart-demo
需求:
store/modules/cart.js
export default {
namespaced: true,
state () {
return {
list: []
}
},
}
store/cart.js
import Vuex from 'vuex'
import Vue from 'vue'
import cart from './modules/cart'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
cart
}
})
export default store
yarn global add json-server 或 npm i json-server -g
json-server --watch index.json
请求获取数据存入 vuex, 映射渲染
yarn add axios
import axios from 'axios'
export default {
namespaced: true,
state () {
return {
list: []
}
},
mutations: {
updateList (state, payload) {
state.list = payload
}
},
actions: {
async getList (ctx) {
const res = await axios.get('http://localhost:3000/cart')
ctx.commit('updateList', res.data)
}
}
}
App.vue
页面中调用 action, 获取数据import { mapState } from 'vuex'
export default {
name: 'App',
components: {
CartHeader,
CartFooter,
CartItem
},
created () {
this.$store.dispatch('cart/getList')
},
computed: {
...mapState('cart', ['list'])
}
}
<!-- 商品 Item 项组件 -->
<cart-item v-for="item in list" :key="item.id" :item="item"></cart-item>
cart-item.vue
<template>
<div class="goods-container">
<!-- 左侧图片区域 -->
<div class="left">
<img :src="item.thumb" class="avatar" alt="">
</div>
<!-- 右侧商品区域 -->
<div class="right">
<!-- 标题 -->
<div class="title">{{item.name}}</div>
<div class="info">
<!-- 单价 -->
<span class="price">¥{{item.price}}</span>
<div class="btns">
<!-- 按钮区域 -->
<button class="btn btn-light">-</button>
<span class="count">{{item.count}}</span>
<button class="btn btn-light">+</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'CartItem',
props: {
item: Object
},
methods: {
}
}
</script>
<!-- 按钮区域 -->
<button class="btn btn-light" @click="onBtnClick(-1)">-</button>
<span class="count">{{item.count}}</span>
<button class="btn btn-light" @click="onBtnClick(1)">+</button>
onBtnClick (step) {
const newCount = this.item.count + step
if (newCount < 1) return
// 发送修改数量请求
this.$store.dispatch('cart/updateCount', {
id: this.item.id,
count: newCount
})
}
async updateCount (ctx, payload) {
await axios.patch('http://localhost:3000/cart/' + payload.id, {
count: payload.count
})
ctx.commit('updateCount', payload)
}
mutations: {
...,
updateCount (state, payload) {
const goods = state.list.find((item) => item.id === payload.id)
goods.count = payload.count
}
},
getters: {
total(state) {
return state.list.reduce((p, c) => p + c.count, 0);
},
totalPrice (state) {
return state.list.reduce((p, c) => p + c.count * c.price, 0);
},
},
<template>
<div class="footer-container">
<!-- 中间的合计 -->
<div>
<span>共 {{total}} 件商品,合计:</span>
<span class="price">¥{{totalPrice}}</span>
</div>
<!-- 右侧结算按钮 -->
<button class="btn btn-success btn-settle">结算</button>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
name: 'CartFooter',
computed: {
...mapGetters('cart', ['total', 'totalPrice'])
}
}
</script>
要不断奔跑,希望大家都可以不断努力,到达自己的目的地❤️