- Vue3简介 =========
-
2020年9月18日,
Vue.js
发布版3.0
版本,代号:One Piece
(n -
截止2023年10月,最新的公开版本为:
3.3.4
1.1. 【性能的提升】
-
打包大小减少
41%
。 -
初次渲染快
55%
, 更新渲染快133%
。 -
内存减少
54%
。
1.2.【 源码的升级】
-
使用
Proxy
代替defineProperty
实现响应式。 -
重写虚拟
DOM
的实现和Tree-Shaking
。
1.3. 【拥抱TypeScript】
Vue3
可以更好的支持TypeScript
。
1.4. 【新的特性】
-
Composition API
(组合API
):-
setup
-
ref
与reactive
-
computed
与watch
......
-
-
新的内置组件:
-
Fragment
-
Teleport
-
Suspense
......
-
-
其他改变:
-
新的生命周期钩子
-
data
选项应始终被声明为一个函数 -
移除
keyCode
支持作为v-on
的修饰符......
-
-
创建Vue3工程 ===========
2.1. 【基于 vue-cli 创建】
点击查看官方文档
备注:目前
vue-cli
已处于维护模式,官方推荐基于Vite
创建项目。
## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version
安装或者升级你的@vue/cli
----------------
npm install -g @vue/cli
执行创建命令
------
vue create vue_test
随后选择3.x
-------
Choose a version of Vue.js that you want to start the project with (Use arrow keys)
-----------------------------------------------------------------------------------
\> 3.x
------
2.x
---
启动
---
`cd vue_test
npm run serve`
2.2. 【基于 vite 创建】(推荐)
vite
是新一代前端构建工具,官网地址:https://vitejs.cn,vite
的优势如下:
- 轻量快速的热重载(
HMR
),能实现极速的服务启动。 - 对
TypeScript
、JSX
、CSS
等支持开箱即用。 - 真正的按需编译,不再等待整个应用编译完成。
webpack
构建 与vite
构建对比图如下:
- 具体操作如下(点击查看官方文档)
## 1.创建命令
npm create vue@latest
2.具体配置
------
配置项目名称
------
√ Project name: vue3_test
是否添加TypeScript支持
----------------
√ Add TypeScript? Yes
是否添加JSX支持
---------
√ Add JSX Support? No
是否添加路由环境
--------
√ Add Vue Router for Single Page Application development? No
是否添加pinia环境
-----------
√ Add Pinia for state management? No
是否添加单元测试
--------
√ Add Vitest for Unit Testing? No
是否添加端到端测试方案
-----------
√ Add an End-to-End Testing Solution? \>\> No
是否添加ESLint语法检查
--------------
√ Add ESLint for code quality? Yes
是否添加Prettiert代码格式化
------------------
`√ Add Prettier for code formatting? No`
自己动手编写一个App组件
<template>
<div class="app">
<h1>你好啊!</h1>
</div>
</template>
\<script lang="ts"\>
export default {
name:'App' //组件名
}
\</script\>
`<style>
.app {
background-color: #ddd;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>`
安装官方推荐的vscode
插件:
总结:
-
Vite
项目中,index.html
是项目的入口文件,在项目最外层。 -
加载
index.html
后,Vite
解析<script type="module" src="xxx">
指向的JavaScript
。 -
Vue3
中是通过createApp
函数创建一个应用实例。2.3. 【一个简单的效果】
Vue3
向下兼容Vue2
语法,且Vue3
中的模板中可以没有根标签
<template>
<div class="person">
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">年龄+1</button>
<button @click="showTel">点我查看联系方式</button>
</div>
</template>
`<script lang="ts">
export default {
name:'App',
data() {
return {
name:'张三',
age:18,
tel:'13888888888'
}
},
methods:{
changeName(){
this.name = 'zhang-san'
},
changeAge(){
this.age += 1
},
showTel(){
alert(this.tel)
}
},
}
</script>`
- Vue3核心语法 ===========
3.1. 【OptionsAPI 与 CompositionAPI】
-
Vue2
的API
设计是Options
(配置)风格的。 -
Vue3
的API
设计是Composition
(组合)风格的。Options API 的弊端
Options
类型的 API
,数据、方法、计算属性等,是分散在:data
、methods
、computed
中的,若想新增或者修改一个需求,就需要分别修改:data
、methods
、computed
,不便于维护和复用。
Composition API 的优势
可以用函数的方式,更加优雅的组织代码,让相关功能的代码更加有序的组织在一起。
说明:以上四张动图原创作者:大帅老猿
3.2. 【拉开序幕的 setup】
setup 概述
setup
是Vue3
中一个新的配置项,值是一个函数,它是 MARKDOWN_HASH8651cf3c01cd6648663a8b2e23194843MARKDOWN
HASH***"表演的舞台*** " _,组件中所用到的:数据、方法、计算属性、监视......等等,均配置在setup
中。
特点如下:
-
setup
函数返回的对象中的内容,可直接在模板中使用。 -
setup
中访问this
是undefined
。 -
setup
函数会在beforeCreate
之前调用,它是"领先"所有钩子执行的。<template> <div class="person"> <h2>姓名:{{name}}</h2> <h2>年龄:{{age}}</h2> <button @click="changeName">修改名字</button> <button @click="changeAge">年龄+1</button> <button @click="showTel">点我查看联系方式</button> </div> </template>
<script lang="ts">
export default {
name:'Person',
setup(){
// 数据,原来写在data中(注意:此时的name、age、tel数据都不是响应式数据)
let name = '张三'
let age = 18
let tel = '13888888888'
// 方法,原来写在methods中
function changeName(){
name = 'zhang-san' //注意:此时这么修改name页面是不变化的
console.log(name)
}
function changeAge(){
age += 1 //注意:此时这么修改age页面是不变化的
console.log(age)
}
function showTel(){
alert(tel)
}
`// 返回一个对象,对象中的内容,模板中可以直接使用
return {name,age,tel,changeName,changeAge,showTel}
}`
}
</script>
### setup 的返回值
* 若返回一个对象:则对象中的:属性、方法等,在模板中均可以直接使用**(重点关注)。**
* 若返回一个函数:则可以自定义渲染内容,代码如下:
````jsx
setup(){
return ()=> &#039;你好啊!&#039;
}</code></pre>
<h3>setup 与 Options API 的关系</h3>
<ul>
<li><code>Vue2</code> 的配置(<code>data</code>、<code>methos</code>......)中<strong>可以访问到</strong> <code>setup</code>中的属性、方法。</li>
<li>但在<code>setup</code>中<strong>不能访问到</strong><code>Vue2</code>的配置(<code>data</code>、<code>methos</code>......)。</li>
<li>如果与<code>Vue2</code>冲突,则<code>setup</code>优先。
<h3>setup 语法糖</h3>
<p><code>setup</code>函数有一个语法糖,这个语法糖,可以让我们把<code>setup</code>独立出去,代码如下:</p></li>
</ul>
<pre><code class="language-vue"><template>
<div class="person">
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="changName">修改名字</button>
<button @click="changAge">年龄+1</button>
<button @click="showTel">点我查看联系方式</button>
</div>
</template>
<script lang="ts">
export default {
name:&#039;Person&#039;,
}
</script>
<!-- 下面的写法是setup语法糖 -->
<script setup lang="ts">
console.log(this) //undefined
// 数据(注意:此时的name、age、tel都不是响应式数据)
let name = &#039;张三&#039;
let age = 18
let tel = &#039;13888888888&#039;
// 方法
function changName(){
name = &#039;李四&#039;//注意:此时这么修改name页面是不变化的
}
function changAge(){
console.log(age)
age += 1 //注意:此时这么修改age页面是不变化的
}
function showTel(){
alert(tel)
}
</script></code></pre>
<p>扩展:上述代码,还需要编写一个不写<code>setup</code>的<code>script</code>标签,去指定组件名字,比较麻烦,我们可以借助<code>vite</code>中的插件简化</p>
<ol>
<li>第一步:<code>npm i vite-plugin-vue-setup-extend -D</code></li>
<li>第二步:<code>vite.config.ts</code>
<pre><code class="language-jsx">
import { defineConfig } from &#039;vite&#039;
import VueSetupExtend from &#039;vite-plugin-vue-setup-extend&#039;</code></pre></li>
</ol>
<p>export default defineConfig({
plugins: [ VueSetupExtend() ]
})</p>
<pre><code>
3. 第三步:<code><script setup lang="ts" name="Person"></code>
## 3.3. 【ref 创建:基本类型的响应式数据】
- **作用:**定义响应式变量。
- **语法:**<code>let xxx = ref(初始值)</code>。
- **返回值:**一个<code>RefImpl</code>的实例对象,简称<code>ref对象</code>或<code>ref</code>,<code>ref</code>对象的<code>value</code>**属性是响应式的**。
- **注意点:**
- <code>JS</code>中操作数据需要:<code>xxx.value</code>,但模板中不需要<code>.value</code>,直接使用即可。
- 对于<code>let name = ref(&#039;张三&#039;)</code>来说,<code>name</code>不是响应式的,<code>name.value</code>是响应式的。
```vue
<template>
<div class="person">
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">年龄+1</button>
<button @click="showTel">点我查看联系方式</button>
</div>
</template>
<script setup lang="ts" name="Person">
import {ref} from 'vue'
// name和age是一个RefImpl的实例对象,简称ref对象,它们的value属性是响应式的。
let name = ref('张三')
let age = ref(18)
// tel就是一个普通的字符串,不是响应式的
let tel = '13888888888'
function changeName(){
// JS中操作ref对象时候需要.value
name.value = '李四'
console.log(name.value)
// 注意:name不是响应式的,name.value是响应式的,所以如下代码并不会引起页面的更新。
// name = ref('zhang-san')
}
function changeAge(){
// JS中操作ref对象时候需要.value
age.value += 1
console.log(age.value)
}
function showTel(){
alert(tel)
}
</script></code></pre>
<h2>3.4. 【reactive 创建:对象类型的响应式数据】</h2>
<ul>
<li><strong>作用:</strong>定义一个<strong>响应式对象</strong>(基本类型不要用它,要用<code>ref</code>,否则报错)</li>
<li><strong>语法:</strong><code>let 响应式对象= reactive(源对象)</code>。</li>
<li><strong>返回值:</strong>一个<code>Proxy</code>的实例对象,简称:响应式对象。</li>
<li><strong>注意点:</strong><code>reactive</code>定义的响应式数据是"深层次"的。 <pre><code class="language-vue">
<template>
<div class="person">
<h2>汽车信息:一台{{ car.brand }}汽车,价值{{ car.price }}万</h2>
<h2>游戏列表:</h2>
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
<h2>测试:{{obj.a.b.c.d}}</h2>
<button @click="changeCarPrice">修改汽车价格</button>
<button @click="changeFirstGame">修改第一游戏</button>
<button @click="test">测试</button>
</div>
</template></code></pre></li>
</ul>
<p><script lang="ts" setup name="Person"><br> import { reactive } from 'vue'</p>
<p>// 数据<br> let car = reactive({ brand: '奔驰', price: 100 })<br> let games = reactive([<br> { id: 'ahsgdyfa01', name: '英雄联盟' },<br> { id: 'ahsgdyfa02', name: '王者荣耀' },<br> { id: 'ahsgdyfa03', name: '原神' }<br> ])<br> let obj = reactive({<br> a:{<br> b:{<br> c:{<br> d:666<br> }<br> }<br> }<br> })</p>
<p>function changeCarPrice() {<br> car.price += 10<br> }<br> function changeFirstGame() {<br> games[0].name = '流星蝴蝶剑'<br> }<br> function test(){<br> obj.a.b.c.d = 999<br> }<br> </script></p>
<pre><code>## 3.5. 【ref 创建:对象类型的响应式数据】
- 其实<code>ref</code>接收的数据可以是:**基本类型**、**对象类型**。
- 若<code>ref</code>接收的是对象类型,内部其实也是调用了<code>reactive</code>函数。
```vue
<template>
<div class="person">
<h2>汽车信息:一台{{ car.brand }}汽车,价值{{ car.price }}万</h2>
<h2>游戏列表:</h2>
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
<h2>测试:{{obj.a.b.c.d}}</h2>
<button @click="changeCarPrice">修改汽车价格</button>
<button @click="changeFirstGame">修改第一游戏</button>
<button @click="test">测试</button>
</div>
</template>
<script lang="ts" setup name="Person">
import { ref } from &#039;vue&#039;
// 数据
let car = ref({ brand: &#039;奔驰&#039;, price: 100 })
let games = ref([
{ id: &#039;ahsgdyfa01&#039;, name: &#039;英雄联盟&#039; },
{ id: &#039;ahsgdyfa02&#039;, name: &#039;王者荣耀&#039; },
{ id: &#039;ahsgdyfa03&#039;, name: &#039;原神&#039; }
])
let obj = ref({
a:{
b:{
c:{
d:666
}
}
}
})
console.log(car)
function changeCarPrice() {
car.value.price += 10
}
function changeFirstGame() {
games.value[0].name = &#039;流星蝴蝶剑&#039;
}
function test(){
obj.value.a.b.c.d = 999
}
</script></code></pre>
<h2>3.6. 【ref 对比 reactive】</h2>
<p>宏观角度看:</p>
<blockquote>
<ol>
<li>
<p><code>ref</code>用来定义:<strong>基本类型数据</strong>、<strong>对象类型数据</strong>;</p>
</li>
<li>
<p><code>reactive</code>用来定义:<strong>对象类型数据</strong>。</p>
</li>
</ol>
</blockquote>
<ul>
<li>区别:</li>
</ul>
<blockquote>
<ol>
<li>
<p><code>ref</code>创建的变量必须使用<code>.value</code>(可以使用<code>volar</code>插件自动添加<code>.value</code>)。</p>
<img src="images/自动补充value.png" alt="自动补充value" style="zoom:50%;border-radius:20px" />
</li>
<li>
<p><code>reactive</code>重新分配一个新对象,会<strong>失去</strong>响应式(可以使用<code>Object.assign</code>去整体替换)。</p>
</li>
</ol>
</blockquote>
<ul>
<li>使用原则:
<blockquote>
<ol>
<li>若需要一个基本类型的响应式数据,必须使用<code>ref</code>。</li>
<li>若需要一个响应式对象,层级不深,<code>ref</code>、<code>reactive</code>都可以。</li>
<li>若需要一个响应式对象,且层级较深,推荐使用<code>reactive</code>。</li>
</ol>
</blockquote></li>
</ul>
<h2>3.7. 【toRefs 与 toRef】</h2>
<ul>
<li>作用:将一个响应式对象中的每一个属性,转换为<code>ref</code>对象。</li>
<li>备注:<code>toRefs</code>与<code>toRef</code>功能一致,但<code>toRefs</code>可以批量转换。</li>
<li>语法如下:
<pre><code class="language-vue">
<template>
<div class="person">
<h2>姓名:{{person.name}}</h2>
<h2>年龄:{{person.age}}</h2>
<h2>性别:{{person.gender}}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="changeGender">修改性别</button>
</div>
</template></code></pre></li>
</ul>
<p><script lang="ts" setup name="Person">
import {ref,reactive,toRefs,toRef} from &#039;vue&#039;</p>
<p>// 数据
let person = reactive({name:&#039;张三&#039;, age:18, gender:&#039;男&#039;})</p>
<p>// 通过toRefs将person对象中的n个属性批量取出,且依然保持响应式的能力
let {name,gender} = toRefs(person)</p>
<p>// 通过toRef将person对象中的gender属性取出,且依然保持响应式的能力
let age = toRef(person,&#039;age&#039;)</p>
<p>// 方法
function changeName(){
name.value += &#039;~&#039;
}
function changeAge(){
age.value += 1
}
function changeGender(){
gender.value = &#039;女&#039;
}
</script></p>
<pre><code>## 3.8. 【computed】
作用:根据已有数据计算出新数据(和<code>Vue2</code>中的<code>computed</code>作用一致)。
<img src="images/computed.gif" style="zoom:20%;" />
```vue
<template>
<div class="person">
姓:<input type="text" v-model="firstName"> <br>
名:<input type="text" v-model="lastName"> <br>
全名:<span>{{fullName}}</span> <br>
<button @click="changeFullName">全名改为:li-si</button>
</div>
</template>
<script setup lang="ts" name="App">
import {ref,computed} from 'vue'
let firstName = ref('zhang')
let lastName = ref('san')
// 计算属性------只读取,不修改
/* let fullName = computed(()=>{
return firstName.value + '-' + lastName.value
}) */
// 计算属性------既读取又修改
let fullName = computed({
// 读取
get(){
return firstName.value + '-' + lastName.value
},
// 修改
set(val){
console.log('有人修改了fullName',val)
firstName.value = val.split('-')[0]
lastName.value = val.split('-')[1]
}
})
function changeFullName(){
fullName.value = 'li-si'
}
</script></code></pre>
<h2>3.9.【watch】</h2>
<ul>
<li>作用:监视数据的变化(和<code>Vue2</code>中的<code>watch</code>作用一致)</li>
<li>特点:<code>Vue3</code>中的<code>watch</code>只能监视以下<strong>四种数据</strong>:<br>
<blockquote>
<ol>
<li><code>ref</code>定义的数据。</li>
<li><code>reactive</code>定义的数据。</li>
<li>函数返回一个值(<code>getter</code>函数)。</li>
<li>一个包含上述内容的数组。</li>
</ol>
</blockquote></li>
</ul>
<p>我们在<code>Vue3</code>中使用<code>watch</code>的时候,通常会遇到以下几种情况:</p>
<h3>* 情况一</h3>
<p>监视<code>ref</code>定义的【基本类型】数据:直接写数据名即可,监视的是其<code>value</code>值的改变。</p>
<pre><code class="language-vue"><template>
<div class="person">
<h1>情况一:监视【ref】定义的【基本类型】数据</h1>
<h2>当前求和为:{{sum}}</h2>
<button @click="changeSum">点我sum+1</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,watch} from 'vue'
// 数据
let sum = ref(0)
// 方法
function changeSum(){
sum.value += 1
}
// 监视,情况一:监视【ref】定义的【基本类型】数据
const stopWatch = watch(sum,(newValue,oldValue)=>{
console.log('sum变化了',newValue,oldValue)
if(newValue >= 10){
stopWatch()
}
})
</script></code></pre>
<h3>* 情况二</h3>
<p>监视<code>ref</code>定义的【对象类型】数据:直接写数据名,监视的是对象的【地址值】,若想监视对象内部的数据,要手动开启深度监视。</p>
<blockquote>
<p>注意:</p>
<ul>
<li><p>若修改的是<code>ref</code>定义的对象中的属性,<code>newValue</code> 和 <code>oldValue</code> 都是新值,因为它们是同一个对象。</p></li>
<li><p>若修改整个<code>ref</code>定义的对象,<code>newValue</code> 是新值, <code>oldValue</code> 是旧值,因为不是同一个对象了。</p></li>
</ul>
</blockquote>
<pre><code class="language-vue"><template>
<div class="person">
<h1>情况二:监视【ref】定义的【对象类型】数据</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="changePerson">修改整个人</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,watch} from 'vue'
// 数据
let person = ref({
name:'张三',
age:18
})
// 方法
function changeName(){
person.value.name += '~'
}
function changeAge(){
person.value.age += 1
}
function changePerson(){
person.value = {name:'李四',age:90}
}
/*
监视,情况一:监视【ref】定义的【对象类型】数据,监视的是对象的地址值,若想监视对象内部属性的变化,需要手动开启深度监视
watch的第一个参数是:被监视的数据
watch的第二个参数是:监视的回调
watch的第三个参数是:配置对象(deep、immediate等等.....)
*/
watch(person,(newValue,oldValue)=>{
console.log('person变化了',newValue,oldValue)
},{deep:true})
</script></code></pre>
<h3>* 情况三</h3>
<p>监视<code>reactive</code>定义的【对象类型】数据,且默认开启了深度监视。</p>
<pre><code class="language-vue"><template>
<div class="person">
<h1>情况三:监视【reactive】定义的【对象类型】数据</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="changePerson">修改整个人</button>
<hr>
<h2>测试:{{obj.a.b.c}}</h2>
<button @click="test">修改obj.a.b.c</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {reactive,watch} from 'vue'
// 数据
let person = reactive({
name:'张三',
age:18
})
let obj = reactive({
a:{
b:{
c:666
}
}
})
// 方法
function changeName(){
person.name += '~'
}
function changeAge(){
person.age += 1
}
function changePerson(){
Object.assign(person,{name:'李四',age:80})
}
function test(){
obj.a.b.c = 888
}
// 监视,情况三:监视【reactive】定义的【对象类型】数据,且默认是开启深度监视的
watch(person,(newValue,oldValue)=>{
console.log('person变化了',newValue,oldValue)
})
watch(obj,(newValue,oldValue)=>{
console.log('Obj变化了',newValue,oldValue)
})
</script></code></pre>
<h3>* 情况四</h3>
<p>监视<code>ref</code>或<code>reactive</code>定义的【对象类型】数据中的<strong>某个属性</strong>,注意点如下:</p>
<ol>
<li>若该属性值<strong>不是</strong>【对象类型】,需要写成函数形式。</li>
<li>若该属性值是<strong>依然</strong>是【对象类型】,可直接编,也可写成函数,建议写成函数。</li>
</ol>
<p>结论:监视的要是对象里的属性,那么最好写函数式,注意点:若是对象监视的是地址值,需要关注对象内部,需要手动开启深度监视。</p>
<pre><code class="language-vue"><template>
<div class="person">
<h1>情况四:监视【ref】或【reactive】定义的【对象类型】数据中的某个属性</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<h2>汽车:{{ person.car.c1 }}、{{ person.car.c2 }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="changeC1">修改第一台车</button>
<button @click="changeC2">修改第二台车</button>
<button @click="changeCar">修改整个车</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {reactive,watch} from 'vue'
// 数据
let person = reactive({
name:'张三',
age:18,
car:{
c1:'奔驰',
c2:'宝马'
}
})
// 方法
function changeName(){
person.name += '~'
}
function changeAge(){
person.age += 1
}
function changeC1(){
person.car.c1 = '奥迪'
}
function changeC2(){
person.car.c2 = '大众'
}
function changeCar(){
person.car = {c1:'雅迪',c2:'爱玛'}
}
// 监视,情况四:监视响应式对象中的某个属性,且该属性是基本类型的,要写成函数式
/* watch(()=> person.name,(newValue,oldValue)=>{
console.log('person.name变化了',newValue,oldValue)
}) */
// 监视,情况四:监视响应式对象中的某个属性,且该属性是对象类型的,可以直接写,也能写函数,更推荐写函数
watch(()=>person.car,(newValue,oldValue)=>{
console.log('person.car变化了',newValue,oldValue)
},{deep:true})
</script></code></pre>
<h3>* 情况五</h3>
<p>监视上述的多个数据</p>
<pre><code class="language-vue"><template>
<div class="person">
<h1>情况五:监视上述的多个数据</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<h2>汽车:{{ person.car.c1 }}、{{ person.car.c2 }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="changeC1">修改第一台车</button>
<button @click="changeC2">修改第二台车</button>
<button @click="changeCar">修改整个车</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {reactive,watch} from 'vue'
// 数据
let person = reactive({
name:'张三',
age:18,
car:{
c1:'奔驰',
c2:'宝马'
}
})
// 方法
function changeName(){
person.name += '~'
}
function changeAge(){
person.age += 1
}
function changeC1(){
person.car.c1 = '奥迪'
}
function changeC2(){
person.car.c2 = '大众'
}
function changeCar(){
person.car = {c1:'雅迪',c2:'爱玛'}
}
// 监视,情况五:监视上述的多个数据
watch([()=>person.name,person.car],(newValue,oldValue)=>{
console.log('person.car变化了',newValue,oldValue)
},{deep:true})
</script></code></pre>
<h2>3.10. 【watchEffect】</h2>
<ul>
<li><p>官网:立即运行一个函数,同时响应式地追踪其依赖,并在依赖更改时重新执行该函数。</p></li>
<li><p><code>watch</code>对比<code>watchEffect</code></p>
<blockquote>
<ol>
<li><p>都能监听响应式数据的变化,不同的是监听数据变化的方式不同</p></li>
<li><p><code>watch</code>:要明确指出监视的数据</p></li>
<li><p><code>watchEffect</code>:不用明确指出监视的数据(函数中用到哪些属性,那就监视哪些属性)。</p></li>
</ol>
</blockquote></li>
<li><p>示例代码:</p> <pre><code class="language-vue">
<template>
<div class="person">
<h1>需求:水温达到50℃,或水位达到20cm,则联系服务器</h1>
<h2 id="demo">水温:{{temp}}</h2>
<h2>水位:{{height}}</h2>
<button @click="changePrice">水温+1</button>
<button @click="changeSum">水位+10</button>
</div>
</template>
</code></pre></li>
</ul>
<h2>3.11. 【标签的 ref 属性】</h2>
<p>作用:用于注册模板引用。</p>
<blockquote>
<ul>
<li><p>用在普通<code>DOM</code>标签上,获取的是<code>DOM</code>节点。</p></li>
<li><p>用在组件标签上,获取的是组件实例对象。</p></li>
</ul>
</blockquote>
<p>用在普通<code>DOM</code>标签上:</p>
<pre><code class="language-vue"><template>
<div class="person">
<h1 ref="title1">尚硅谷</h1>
<h2 ref="title2">前端</h2>
<h3 ref="title3">Vue</h3>
<input type="text" ref="inpt"> <br><br>
<button @click="showLog">点我打印内容</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref} from 'vue'
let title1 = ref()
let title2 = ref()
let title3 = ref()
function showLog(){
// 通过id获取元素
const t1 = document.getElementById('title1')
// 打印内容
console.log((t1 as HTMLElement).innerText)
console.log((<HTMLElement>t1).innerText)
console.log(t1?.innerText)
/************************************/
// 通过ref获取元素
console.log(title1.value)
console.log(title2.value)
console.log(title3.value)
}
</script></code></pre>
<p>用在组件标签上:</p>
<pre><code class="language-vue"><!-- 父组件App.vue -->
<template>
<Person ref="ren"/>
<button @click="test">测试</button>
</template>
<script lang="ts" setup name="App">
import Person from './components/Person.vue'
import {ref} from 'vue'
let ren = ref()
function test(){
console.log(ren.value.name)
console.log(ren.value.age)
}
</script>
<!-- 子组件Person.vue中要使用defineExpose暴露内容 -->
<script lang="ts" setup name="Person">
import {ref,defineExpose} from 'vue'
// 数据
let name = ref('张三')
let age = ref(18)
/****************************/
/****************************/
// 使用defineExpose将组件中的数据交给外部
defineExpose({name,age})
</script></code></pre>
<h2>3.12. 【props】</h2>
<blockquote>
<pre><code class="language-js">// 定义一个接口,限制每个Person对象的格式
export interface PersonInter {
id:string,
name:string,
age:number
}
// 定义一个自定义类型Persons
export type Persons = Array
<personinter></personinter></code></pre>
<p><code>App.vue</code>中代码:</p>
<pre><code class="language-vue">
<template>
<person :list="persons" />
</template>
</code></pre>
<p><code>Person.vue</code>中代码:</p>
<pre><code class="language-Vue">
<template>
<div class="person">
<ul>
<li v-for="item in list" :key="item.id">
{{item.name}}--{{item.age}}
</li>
</ul>
</div>
</template>
</code></pre>
</blockquote>
<h2>3.13. 【生命周期】</h2>
<ul>
<li><p>概念:<code>Vue</code>组件实例在创建时要经历一系列的初始化步骤,在此过程中<code>Vue</code>会在合适的时机,调用特定的函数,从而让开发者有机会在特定阶段运行自己的代码,这些特定的函数统称为:生命周期钩子</p></li>
<li><p>规律:</p>
<blockquote>
<p>生命周期整体分为四个阶段,分别是:<strong>创建、挂载、更新、销毁</strong>,每个阶段都有两个钩子,一前一后。</p>
</blockquote></li>
<li><p><code>Vue2</code>的生命周期</p>
<blockquote>
<p>创建阶段:<code>beforeCreate</code>、<code>created</code></p>
<p>挂载阶段:<code>beforeMount</code>、<code>mounted</code></p>
<p>更新阶段:<code>beforeUpdate</code>、<code>updated</code></p>
<p>销毁阶段:<code>beforeDestroy</code>、<code>destroyed</code></p>
</blockquote></li>
<li><p><code>Vue3</code>的生命周期</p>
<blockquote>
<p>创建阶段:<code>setup</code></p>
<p>挂载阶段:<code>onBeforeMount</code>、<code>onMounted</code></p>
<p>更新阶段:<code>onBeforeUpdate</code>、<code>onUpdated</code></p>
<p>卸载阶段:<code>onBeforeUnmount</code>、<code>onUnmounted</code></p>
</blockquote></li>
<li><p>常用的钩子:<code>onMounted</code>(挂载完毕)、<code>onUpdated</code>(更新完毕)、<code>onBeforeUnmount</code>(卸载之前)</p></li>
<li><p>示例代码:</p> <pre><code class="language-vue">
<template>
<div class="person">
<h2>当前求和为:{{ sum }}</h2>
<button @click="changeSum">点我sum+1</button>
</div>
</template>
<!-- vue3写法 -->
</code></pre></li>
</ul>
<h2>3.14. 【自定义hook】</h2>
<ul>
<li><p>什么是<code>hook</code>?------ 本质是一个函数,把<code>setup</code>函数中使用的<code>Composition API</code>进行了封装,类似于<code>vue2.x</code>中的<code>mixin</code>。</p></li>
<li><p>自定义<code>hook</code>的优势:复用代码, 让<code>setup</code>中的逻辑更清楚易懂。</p></li>
</ul>
<p>示例代码:</p>
<ul>
<li><p><code>useSum.ts</code>中内容如下:</p> <pre><code class="language-js">import {ref,onMounted} from 'vue'
export default function(){
let sum = ref(0)
const increment = ()=>{
sum.value += 1
}
const decrement = ()=>{
sum.value -= 1
}
onMounted(()=>{
increment()
})
//向外部暴露数据
return {sum,increment,decrement}
} </code></pre></li>
<li><p><code>useDog.ts</code>中内容如下:</p> <pre><code class="language-js">import {reactive,onMounted} from 'vue'
import axios,{AxiosError} from 'axios'
export default function(){
let dogList = reactive
<string[]>([])
// 方法
async function getDog(){
try {
// 发请求
let {data} = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
// 维护数据
dogList.push(data.message)
} catch (error) {
// 处理错误
const err =
<axioserror>error
console.log(err.message)
}
}
// 挂载钩子
onMounted(()=>{
getDog()
})
//向外部暴露数据
return {dogList,getDog}
}
</axioserror>
</string[]></code></pre></li>
<li><p>组件中具体使用:</p> <pre><code class="language-vue">
<template>
<h2>当前求和为:{{sum}}</h2>
<button @click="increment">点我+1</button>
<button @click="decrement">点我-1</button>
<hr>
<img v-for="(u,index) in dogList.urlList" :key="index" :src="(u as string)">
<span v-show="dogList.isLoading">加载中......</span><br>
<button @click="getDog">再来一只狗</button>
</template>
</code></pre></li>
</ul>
<hr>
<h1>4. 路由</h1>
<h2>4.1. 【对路由的理解】</h2>
<p><img decoding="async" src="images/image-20231018144351536.png" alt="image-20231018144351536" style="zoom:20%;border-radius:40px"></p>
<h2>4.2. 【基本切换效果】</h2>
<ul>
<li><p><code>Vue3</code>中要使用<code>vue-router</code>的最新版本,目前是<code>4</code>版本。</p></li>
<li><p>路由配置文件代码如下:</p> <pre><code class="language-js">import {createRouter,createWebHistory} from 'vue-router'
import Home from '@/pages/Home.vue'
import News from '@/pages/News.vue'
import About from '@/pages/About.vue'
const router = createRouter({
history:createWebHistory(),
routes:[
{
path:'/home',
component:Home
},
{
path:'/about',
component:About
}
]
})
export default router</code></pre></li>
<li><p><code>main.ts</code>代码如下:</p> <pre><code class="language-js">import router from './router/index'
app.use(router)
app.mount('#app')</code></pre></li>
<li><p><code>App.vue</code>代码如下</p> <pre><code class="language-vue">
<template>
<div class="app">
<h2 class="title">Vue路由测试</h2>
<!-- 导航区 -->
<div class="navigate">
<routerlink to="/home" active-class="active">首页
</routerlink>
<routerlink to="/news" active-class="active">新闻
</routerlink>
<routerlink to="/about" active-class="active">关于
</routerlink>
</div>
<!-- 展示区 -->
<div class="main-content">
<routerview />
</div>
</div>
</template>
</code></pre></li>
</ul>
<h2>4.3. 【两个注意点】</h2>
<blockquote>
<ol>
<li><p>路由组件通常存放在<code>pages</code> 或 <code>views</code>文件夹,一般组件通常存放在<code>components</code>文件夹。</p></li>
<li><p>通过点击导航,视觉效果上"消失" 了的路由组件,默认是被<strong>卸载</strong>掉的,需要的时候再去<strong>挂载</strong>。</p></li>
</ol>
</blockquote>
<h2>4.4.【路由器工作模式】</h2>
<ol>
<li><p><code>history</code>模式</p>
<blockquote>
<p>优点:<code>URL</code>更加美观,不带有<code>#</code>,更接近传统的网站<code>URL</code>。</p>
<p>缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有<code>404</code>错误。</p>
<pre><code class="language-js">const router = createRouter({
history:createWebHistory(), //history模式
/******/
})</code></pre>
</blockquote></li>
<li><p><code>hash</code>模式</p>
<blockquote>
<p>优点:兼容性更好,因为不需要服务器端处理路径。</p>
<p>缺点:<code>URL</code>带有<code>#</code>不太美观,且在<code>SEO</code>优化方面相对较差。</p>
<pre><code class="language-js">const router = createRouter({
history:createWebHashHistory(), //hash模式
/******/
})</code></pre>
</blockquote></li>
</ol>
<h2>4.5. 【to的两种写法】</h2>
<pre><code class="language-vue"><!-- 第一种:to的字符串写法 -->
<router-link active-class="active" to="/home">主页</router-link>
<!-- 第二种:to的对象写法 -->
<router-link active-class="active" :to="{path:'/home'}">Home</router-link></code></pre>
<h2>4.6. 【命名路由】</h2>
<p>作用:可以简化路由跳转及传参(后面就讲)。</p>
<p>给路由规则命名:</p>
<pre><code class="language-js">routes:[
{
name:'zhuye',
path:'/home',
component:Home
},
{
name:'xinwen',
path:'/news',
component:News,
},
{
name:'guanyu',
path:'/about',
component:About
}
]</code></pre>
<p>跳转路由:</p>
<pre><code class="language-vue"><!--简化前:需要写完整的路径(to的字符串写法) -->
<router-link to="/news/detail">跳转</router-link>
<!--简化后:直接通过名字跳转(to的对象写法配合name属性) -->
<router-link :to="{name:'guanyu'}">跳转</router-link></code></pre>
<h2>4.7. 【嵌套路由】</h2>
<ol>
<li><p>编写<code>News</code>的子路由:<code>Detail.vue</code></p></li>
<li><p>配置路由规则,使用<code>children</code>配置项:</p> <pre><code class="language-ts">const router = createRouter({
history:createWebHistory(),
routes:[
{
name:'zhuye',
path:'/home',
component:Home
},
{
name:'xinwen',
path:'/news',
component:News,
children:[
{
name:'xiang',
path:'detail',
component:Detail
}
]
},
{
name:'guanyu',
path:'/about',
component:About
}
]
})
export default router</code></pre></li>
<li><p>跳转路由(记得要加完整路径):</p> <pre><code class="language-vue">
<router-link to="/news/detail">xxxx
</router-link>
<!-- 或 -->
<router-link :to="{path:'/news/detail'}">xxxx
</router-link></code></pre></li>
<li><p>记得去<code>Home</code>组件中预留一个<code><router-view></code></p> <pre><code class="language-vue">
<template>
<div class="news">
<nav class="news-list">
<routerlink v-for="news in newsList" :key="news.id" :to="{path:'/news/detail'}">
{{news.name}}
</routerlink>
</nav>
<div class="news-detail">
<routerview />
</div>
</div>
</template></code></pre></li>
</ol>
<h2>4.8. 【路由传参】</h2>
<h3>query参数</h3>
<ol>
<li><p>传递参数</p> <pre><code class="language-vue"> <!-- 跳转并携带query参数(to的字符串写法) -->
<router-link to="/news/detail?a=1&b=2&content=欢迎你">
跳转
</router-link>
<!-- 跳转并携带query参数(to的对象写法) -->
<routerlink :to="{
//name:'xiang', //用name也可以跳转
path:'/news/detail',
query:{
id:news.id,
title:news.title,
content:news.content
}
}">
{{news.title}}
</routerlink></code></pre></li>
<li><p>接收参数:</p> <pre><code class="language-js"> import {useRoute} from 'vue-router'
const route = useRoute()
// 打印query参数
console.log(route.query)</code></pre></li>
</ol>
<h3>params参数</h3>
<ol>
<li><p>传递参数</p> <pre><code class="language-vue"> <!-- 跳转并携带params参数(to的字符串写法) -->
<routerlink :to="<code>/news/detail/001/新闻001/内容001</code>">{{news.title}}
</routerlink>
<!-- 跳转并携带params参数(to的对象写法) -->
<routerlink :to="{
name:'xiang', //用name跳转
params:{
id:news.id,
title:news.title,
content:news.title
}
}">
{{news.title}}
</routerlink></code></pre></li>
<li><p>接收参数:</p> <pre><code class="language-js"> import {useRoute} from 'vue-router'
const route = useRoute()
// 打印params参数
console.log(route.params)</code></pre></li>
</ol>
<blockquote>
<p>备注1:传递<code>params</code>参数时,若使用<code>to</code>的对象写法,必须使用<code>name</code>配置项,不能用<code>path</code>。</p>
<p>备注2:传递<code>params</code>参数时,需要提前在规则中占位。</p>
</blockquote>
<h2>4.9. 【路由的props配置】</h2>
<p>作用:让路由组件更方便的收到参数(可以将路由参数作为<code>props</code>传给组件)</p>
<pre><code class="language-js">{
name:'xiang',
path:'detail/:id/:title/:content',
component:Detail,
// props的对象写法,作用:把对象中的每一组key-value作为props传给Detail组件
// props:{a:1,b:2,c:3},
// props的布尔值写法,作用:把收到了每一组params参数,作为props传给Detail组件
// props:true
// props的函数写法,作用:把返回的对象中每一组key-value作为props传给Detail组件
props(route){
return route.query
}
}</code></pre>
<h2>4.10. 【 replace属性】</h2>
<ol>
<li><p>作用:控制路由跳转时操作浏览器历史记录的模式。</p></li>
<li><p>浏览器的历史记录有两种写入方式:分别为<code><code>push</code>`<code>和</code>`<code>replace</code></code>:</p>
<ul>
<li><code><code>push</code></code>是追加历史记录(默认值)。</li>
<li><code>replace</code>是替换当前记录。</li>
</ul></li>
<li><p>开启<code>replace</code>模式:</p> <pre><code class="language-vue">
<routerlink replace .......>News
</routerlink></code></pre></li>
</ol>
<h2>4.11. 【编程式导航】</h2>
<p>路由组件的两个重要的属性:<code>$route</code>和<code>$router</code>变成了两个<code>hooks</code></p>
<pre><code class="language-js">import {useRoute,useRouter} from 'vue-router'
const route = useRoute()
const router = useRouter()
console.log(route.query)
console.log(route.parmas)
console.log(router.push)
console.log(router.replace)</code></pre>
<h2>4.12. 【重定向】</h2>
<ol>
<li><p>作用:将特定的路径,重新定向到已有路由。</p></li>
<li><p>具体编码:</p> <pre><code class="language-js">{
path:'/',
redirect:'/about'
}</code></pre></li>
</ol>
<h1>5. pinia</h1>
<h2>5.1【准备一个效果】</h2>
<p><img decoding="async" src="./images/pinia_example.gif" alt="pinia_example" style="zoom:30%;border:3px solid"></p>
<h2>5.2【搭建 pinia 环境】</h2>
<p>第一步:<code>npm install pinia</code></p>
<p>第二步:操作<code>src/main.ts</code></p>
<pre><code class="language-ts">import { createApp } from 'vue'
import App from './App.vue'
/* 引入createPinia,用于创建pinia */
import { createPinia } from 'pinia'
/* 创建pinia */
const pinia = createPinia()
const app = createApp(App)
/* 使用插件 */{}
app.use(pinia)
app.mount('#app')</code></pre>
<p>此时开发者工具中已经有了<code>pinia</code>选项</p>
<p><img decoding="async" src="https://cdn.nlark.com/yuque/0/2023/png/35780599/1684309952481-c67f67f9-d1a3-4d69-8bd6-2b381e003f31.png" style="zoom:80%;border:1px solid black;border-radius:10px"></p>
<h2>5.3【存储+读取数据】</h2>
<ol>
<li><p><code>Store</code>是一个保存:<strong>状态</strong>、<strong>业务逻辑</strong> 的实体,每个组件都可以<strong>读取</strong>、<strong>写入</strong>它。</p></li>
<li><p>它有三个概念:<code>state</code>、<code>getter</code>、<code>action</code>,相当于组件中的: <code>data</code>、 <code>computed</code> 和 <code>methods</code>。</p></li>
<li><p>具体编码:<code>src/store/count.ts</code></p> <pre><code class="language-ts">// 引入defineStore用于创建store
import {defineStore} from 'pinia'
// 定义并暴露一个store
export const useCountStore = defineStore('count',{
// 动作
actions:{},
// 状态
state(){
return {
sum:6
}
},
// 计算
getters:{}
})</code></pre></li>
<li><p>具体编码:<code>src/store/talk.ts</code></p> <pre><code class="language-js">// 引入defineStore用于创建store
import {defineStore} from 'pinia'
// 定义并暴露一个store
export const useTalkStore = defineStore('talk',{
// 动作
actions:{},
// 状态
state(){
return {
talkList:[
{id:'yuysada01',content:'你今天有点怪,哪里怪?怪好看的!'},
{id:'yuysada02',content:'草莓、蓝莓、蔓越莓,你想我了没?'},
{id:'yuysada03',content:'心里给你留了一块地,我的死心塌地'}
]
}
},
// 计算
getters:{}
})</code></pre></li>
<li><p>组件中使用<code>state</code>中的数据</p> <pre><code class="language-vue">
<template>
<h2>当前求和为:{{ sumStore.sum }}</h2>
</template>
</code></pre> <pre><code class="language-vue">
<template>
<ul>
<li v-for="talk in talkStore.talkList" :key="talk.id">
{{ talk.content }}
</li>
</ul>
</template>
</code></pre></li>
</ol>
<h2>5.4.【修改数据】(三种方式)</h2>
<ol>
<li><p>第一种修改方式,直接修改</p> <pre><code class="language-ts">countStore.sum = 666</code></pre></li>
<li><p>第二种修改方式:批量修改</p> <pre><code class="language-ts">countStore.$patch({
sum:999,
school:'atguigu'
})</code></pre></li>
<li><p>第三种修改方式:借助<code>action</code>修改(<code>action</code>中可以编写一些业务逻辑)</p> <pre><code class="language-js">import { defineStore } from 'pinia'
export const useCountStore = defineStore('count', {
/*************/
actions: {
//加
increment(value:number) {
if (this.sum < 10) {
//操作countStore中的sum
this.sum += value
}
},
//减
decrement(value:number){
if(this.sum > 1){
this.sum -= value
}
}
},
/*************/
})</code></pre></li>
<li><p>组件中调用<code>action</code>即可</p> <pre><code class="language-js">// 使用countStore
const countStore = useCountStore()
// 调用对应action
countStore.incrementOdd(n.value)</code></pre></li>
</ol>
<h2>5.5.【storeToRefs】</h2>
<ul>
<li>借助<code>storeToRefs</code>将<code>store</code>中的数据转为<code>ref</code>对象,方便在模板中使用。</li>
<li>注意:<code>pinia</code>提供的<code>storeToRefs</code>只会将数据做转换,而<code>Vue</code>的<code>toRefs</code>会转换<code>store</code>中数据。</li>
</ul>
<pre><code class="language-vue"><template>
<div class="count">
<h2>当前求和为:{{sum}}</h2>
</div>
</template>
<script setup lang="ts" name="Count">
import { useCountStore } from '@/store/count'
/* 引入storeToRefs */
import { storeToRefs } from 'pinia'
/* 得到countStore */
const countStore = useCountStore()
/* 使用storeToRefs转换countStore,随后解构 */
const {sum} = storeToRefs(countStore)
</script>
</code></pre>
<h2>5.6.【getters】</h2>
<ol>
<li><p>概念:当<code>state</code>中的数据,需要经过处理后再使用时,可以使用<code>getters</code>配置。</p></li>
<li><p>追加<code><code>getters</code></code>配置。</p> <pre><code class="language-js"> // 引入defineStore用于创建store
import {defineStore} from 'pinia'
// 定义并暴露一个store
export const useCountStore = defineStore('count',{
// 动作
actions:{
/************/
},
// 状态
state(){
return {
sum:1,
school:'atguigu'
}
},
// 计算
getters:{
bigSum:(state):number => state.sum *10,
upperSchool():string{
return this. school.toUpperCase()
}
}
})</code></pre></li>
<li><p>组件中读取数据:</p> <pre><code class="language-js"> const {increment,decrement} = countStore
let {sum,school,bigSum,upperSchool} = storeToRefs(countStore)</code></pre></li>
</ol>
<h2>5.7.【$subscribe】</h2>
<p>通过 store 的 <code>$subscribe()</code> 方法侦听 <code>state</code> 及其变化</p>
<pre><code class="language-ts">talkStore.$subscribe((mutate,state)=>{
console.log('LoveTalk',mutate,state)
localStorage.setItem('talk',JSON.stringify(talkList.value))
})</code></pre>
<h2>5.8. 【store组合式写法】</h2>
<pre><code class="language-ts">import {defineStore} from 'pinia'
import axios from 'axios'
import {nanoid} from 'nanoid'
import {reactive} from 'vue'
export const useTalkStore = defineStore('talk',()=>{
// talkList就是state
const talkList = reactive(
JSON.parse(localStorage.getItem('talkList') as string) || []
)
// getATalk函数相当于action
async function getATalk(){
// 发请求,下面这行的写法是:连续解构赋值+重命名
let {data:{content:title}} = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json')
// 把请求回来的字符串,包装成一个对象
let obj = {id:nanoid(),title}
// 放到数组中
talkList.unshift(obj)
}
return {talkList,getATalk}
})</code></pre>
<h1>6. 组件通信</h1>
<p><strong><code>Vue3</code>组件通信和<code>Vue2</code>的区别:</strong></p>
<ul>
<li><p>移出事件总线,使用<code>mitt</code>代替。</p></li>
<li><p><code>vuex</code>换成了<code>pinia</code>。</p></li>
<li><p>把<code>.sync</code>优化到了<code>v-model</code>里面了。</p></li>
<li><p>把<code>$listeners</code>所有的东西,合并到<code>$attrs</code>中了。</p></li>
<li><p><code>$children</code>被砍掉了。</p></li>
</ul>
<p><strong>常见搭配形式:</strong></p>
<p><img decoding="async" src="images/image-20231119185900990.png" alt="image-20231119185900990" style="zoom:60%;"></p>
<h2>6.1. 【props】</h2>
<p>概述:<code>props</code>是使用频率最高的一种通信方式,常用与 :<strong>父 ↔ 子</strong>。</p>
<ul>
<li>若 <strong>父传子</strong>:属性值是<strong>非函数</strong>。</li>
<li>若 <strong>子传父</strong>:属性值是<strong>函数</strong>。</li>
</ul>
<p>父组件:</p>
<pre><code class="language-vue"><template>
<div class="father">
<h3>父组件,</h3>
<h4>我的车:{{ car }}</h4>
<h4>儿子给的玩具:{{ toy }}</h4>
<Child :car="car" :getToy="getToy"/>
</div>
</template>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";
// 数据
const car = ref('奔驰')
const toy = ref()
// 方法
function getToy(value:string){
toy.value = value
}
</script></code></pre>
<p>子组件</p>
<pre><code class="language-vue"><template>
<div class="child">
<h3>子组件</h3>
<h4>我的玩具:{{ toy }}</h4>
<h4>父给我的车:{{ car }}</h4>
<button @click="getToy(toy)">玩具给父亲</button>
</div>
</template>
<script setup lang="ts" name="Child">
import { ref } from "vue";
const toy = ref('奥特曼')
defineProps(['car','getToy'])
</script></code></pre>
<h2>6.2. 【自定义事件】</h2>
<ol>
<li>概述:自定义事件常用于:<strong>子 => 父。</strong></li>
<li>注意区分好:原生事件、自定义事件。</li>
</ol>
<ul>
<li>原生事件:
<ul>
<li>事件名是特定的(<code>click</code>、<code>mosueenter</code>等等)</li>
<li>事件对象<code>$event</code>: 是包含事件相关信息的对象(<code>pageX</code>、<code>pageY</code>、<code>target</code>、<code>keyCode</code>)</li>
</ul></li>
<li>自定义事件:
<ul>
<li>事件名是任意名称</li>
<li><strong style="color:red">事件对象<code>$event</code>: 是调用<code>emit</code>时所提供的数据,可以是任意类型!!!</strong></li>
</ul></li>
</ul>
<ol start="3">
<li><p>示例:</p> <pre><code class="language-html"><!--在父组件中,给子组件绑定自定义事件:-->
<child @send-toy="toy = $event" />
<!--注意区分原生事件与自定义事件中的$event-->
<button @click="toy = $event">测试</button></code></pre> <pre><code class="language-js">//子组件中,触发事件:
this.$emit('send-toy', 具体数据)</code></pre></li>
</ol>
<h2>6.3. 【mitt】</h2>
<p>概述:与消息订阅与发布(<code>pubsub</code>)功能类似,可以实现任意组件间通信。</p>
<p>安装<code>mitt</code></p>
<pre><code class="language-shell">npm i mitt</code></pre>
<p>新建文件:<code>src\utils\emitter.ts</code></p>
<pre><code class="language-javascript">// 引入mitt
import mitt from "mitt";
// 创建emitter
const emitter = mitt()
/*
// 绑定事件
emitter.on('abc',(value)=>{
console.log('abc事件被触发',value)
})
emitter.on('xyz',(value)=>{
console.log('xyz事件被触发',value)
})
setInterval(() => {
// 触发事件
emitter.emit('abc',666)
emitter.emit('xyz',777)
}, 1000);
setTimeout(() => {
// 清理事件
emitter.all.clear()
}, 3000);
*/
// 创建并暴露mitt
export default emitter</code></pre>
<p>接收数据的组件中:绑定事件、同时在销毁前解绑事件:</p>
<pre><code class="language-typescript">import emitter from "@/utils/emitter";
import { onUnmounted } from "vue";
// 绑定事件
emitter.on('send-toy',(value)=>{
console.log('send-toy事件被触发',value)
})
onUnmounted(()=>{
// 解绑事件
emitter.off('send-toy')
})</code></pre>
<p>【第三步】:提供数据的组件,在合适的时候触发事件</p>
<pre><code class="language-javascript">import emitter from "@/utils/emitter";
function sendToy(){
// 触发事件
emitter.emit('send-toy',toy.value)
}</code></pre>
<p><strong>注意这个重要的内置关系,总线依赖着这个内置关系</strong></p>
<h2>6.4.【v-model】</h2>
<ol>
<li><p>概述:实现 <strong>父↔子</strong> 之间相互通信。</p></li>
<li><p>前序知识 ------ <code>v-model</code>的本质</p> <pre><code class="language-vue"><!-- 使用v-model指令 -->
<input type="text" v-model="userName">
<!-- v-model的本质是下面这行代码 -->
<input type="text" :value="userName" @input="userName =(<HTMLInputElement>$event.target).value"></code></pre></li>
<li><p>组件标签上的<code>v-model</code>的本质:<code>:moldeValue</code> + <code>update:modelValue</code>事件。</p> <pre><code class="language-vue"><!-- 组件标签上使用v-model指令 -->
<atguiguinput v-model="userName" />
<!-- 组件标签上v-model的本质 -->
<atguiguinput :modelvalue="userName" @update:model-value="userName = $event" /></code></pre> <p><code>AtguiguInput</code>组件中:</p> <pre><code class="language-vue">
<template>
<div class="box">
<!--将接收的value值赋给input元素的value属性,目的是:为了呈现数据 -->
<!--给input元素绑定原生input事件,触发input事件时,进而触发update:model-value事件-->
<input type="text" :value="modelValue" @input="emit('update:model-value',$event.target.value)">
</div>
</template>
</code></pre></li>
<li><p>也可以更换<code>value</code>,例如改成<code>abc</code></p> <pre><code class="language-vue"><!-- 也可以更换value,例如改成abc-->
<atguiguinput v-model:abc="userName" />
<!-- 上面代码的本质如下 -->
<atguiguinput :abc="userName" @update:abc="userName = $event" /></code></pre> <p><code>AtguiguInput</code>组件中:</p> <pre><code class="language-vue">
<template>
<div class="box">
<input type="text" :value="abc" @input="emit('update:abc',$event.target.value)">
</div>
</template>
</code></pre></li>
<li><p>如果<code>value</code>可以更换,那么就可以在组件标签上多次使用<code>v-model</code></p> <pre><code class="language-vue">
<atguiguinput v-model:abc="userName" v-model:xyz="password" /></code></pre></li>
</ol>
<h2>6.5.【$attrs 】</h2>
<ol>
<li><p>概述:<code>$attrs</code>用于实现<strong>当前组件的父组件</strong>,向<strong>当前组件的子组件</strong>通信(<strong>祖→孙</strong>)。</p></li>
<li><p>具体说明:<code>$attrs</code>是一个对象,包含所有父组件传入的标签属性。</p>
<blockquote>
<p>注意:<code>$attrs</code>会自动排除<code>props</code>中声明的属性(可以认为声明过的 <code>props</code> 被子组件自己"消费"了)</p>
</blockquote></li>
</ol>
<p>父组件:</p>
<pre><code class="language-vue"><template>
<div class="father">
<h3>父组件</h3>
<Child :a="a" :b="b" :c="c" :d="d" v-bind="{x:100,y:200}" :updateA="updateA"/>
</div>
</template>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";
let a = ref(1)
let b = ref(2)
let c = ref(3)
let d = ref(4)
function updateA(value){
a.value = value
}
</script></code></pre>
<p>子组件:</p>
<pre><code class="language-vue"><template>
<div class="child">
<h3>子组件</h3>
<GrandChild v-bind="$attrs"/>
</div>
</template>
<script setup lang="ts" name="Child">
import GrandChild from './GrandChild.vue'
</script></code></pre>
<p>孙组件:</p>
<pre><code class="language-vue"><template>
<div class="grand-child">
<h3>孙组件</h3>
<h4>a:{{ a }}</h4>
<h4>b:{{ b }}</h4>
<h4>c:{{ c }}</h4>
<h4>d:{{ d }}</h4>
<h4>x:{{ x }}</h4>
<h4>y:{{ y }}</h4>
<button @click="updateA(666)">点我更新A</button>
</div>
</template>
<script setup lang="ts" name="GrandChild">
defineProps(['a','b','c','d','x','y','updateA'])
</script></code></pre>
<h2>6.6. 【$refs、$parent】</h2>
<ol>
<li><p>概述:</p>
<ul>
<li><code>$refs</code>用于 :<strong>父→子。</strong></li>
<li><code>$parent</code>用于:<strong>子→父。</strong></li>
</ul></li>
<li><p>原理如下:</p>
<table>
<thead>
<tr>
<th>属性</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>$refs</code></td>
<td>值为对象,包含所有被<code>ref</code>属性标识的<code>DOM</code>元素或组件实例。</td>
</tr>
<tr>
<td><code>$parent</code></td>
<td>值为对象,当前组件的父组件实例对象。</td>
</tr>
</tbody>
</table></li>
</ol>
<h2>6.7. 【provide、inject】</h2>
<ol>
<li><p>概述:实现<strong>祖孙组件</strong>直接通信</p></li>
<li><p>具体使用:</p>
<ul>
<li>在祖先组件中通过<code>provide</code>配置向后代组件提供数据</li>
<li>在后代组件中通过<code>inject</code>配置来声明接收数据</li>
</ul></li>
<li><p>具体编码:</p> <p>【第一步】父组件中,使用<code>provide</code>提供数据</p> <pre><code class="language-vue">
<template>
<div class="father">
<h3>父组件</h3>
<h4>资产:{{ money }}</h4>
<h4>汽车:{{ car }}</h4>
<button @click="money += 1">资产+1</button>
<button @click="car.price += 1">汽车价格+1</button>
<child />
</div>
</template>
</code></pre>
<blockquote>
<p>注意:子组件中不用编写任何东西,是不受到任何打扰的</p>
</blockquote> <p>【第二步】孙组件中使用<code>inject</code>配置项接受数据。</p> <pre><code class="language-vue">
<template>
<div class="grand-child">
<h3>我是孙组件</h3>
<h4>资产:{{ money }}</h4>
<h4>汽车:{{ car }}</h4>
<button @click="updateMoney(6)">点我</button>
</div>
</template>
</code></pre></li>
</ol>
<h2>6.8. 【pinia】</h2>
<p>参考之前<code>pinia</code>部分的讲解</p>
<h2>6.9. 【slot】</h2>
<h3>1. 默认插槽</h3>
<p><img decoding="async" src="http://49.232.112.44/images/default_slot.png" alt="img"></p>
<pre><code class="language-vue">父组件中:
<Category title="今日热门游戏">
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
</Category>
子组件中:
<template>
<div class="item">
<h3>{{ title }}</h3>
<!-- 默认插槽 -->
<slot></slot>
</div>
</template></code></pre>
<h3>2. 具名插槽</h3>
<pre><code class="language-vue">父组件中:
<Category title="今日热门游戏">
<template v-slot:s1>
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
</template>
<template #s2>
<a href="">更多</a>
</template>
</Category>
子组件中:
<template>
<div class="item">
<h3>{{ title }}</h3>
<slot name="s1"></slot>
<slot name="s2"></slot>
</div>
</template></code></pre>
<h3>3. 作用域插槽</h3>
<ol>
<li><p>理解:<span style="color:red">数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。</span>(新闻数据在<code>News</code>组件中,但使用数据所遍历出来的结构由<code>App</code>组件决定)</p></li>
<li><p>具体编码:</p> <pre><code class="language-vue">父组件中:
<game v-slot="params">
<!-- <Game v-slot:default="params"> -->
<!-- <Game #default="params"> -->
<ul>
<li v-for="g in params.games" :key="g.id">{{ g.name }}</li>
</ul>
</game>
子组件中:
<template>
<div class="category">
<h2>今日游戏榜单</h2>
<slot :games="games" a="哈哈"></slot>
</div>
</template>
</code></pre></li>
</ol>
<h1>7. 其它 API</h1>
<h2>7.1.【shallowRef 与 shallowReactive 】</h2>
<h3><code>shallowRef</code></h3>
<ol>
<li><p>作用:创建一个响应式数据,但只对顶层属性进行响应式处理。</p></li>
<li><p>用法:</p> <pre><code class="language-js">let myVar = shallowRef(initialValue);</code></pre></li>
<li><p>特点:只跟踪引用值的变化,不关心值内部的属性变化。</p></li>
</ol>
<h3><code>shallowReactive</code></h3>
<ol>
<li><p>作用:创建一个浅层响应式对象,只会使对象的最顶层属性变成响应式的,对象内部的嵌套属性则不会变成响应式的</p></li>
<li><p>用法:</p> <pre><code class="language-js">const myObj = shallowReactive({ ... });</code></pre></li>
<li><p>特点:对象的顶层属性是响应式的,但嵌套对象的属性不是。</p></li>
</ol>
<h3>总结</h3>
<blockquote>
<p>通过使用 <a href="https://cn.vuejs.org/api/reactivity-advanced.html#shallowref" target="_blank" rel="nofollow"><code>shallowRef()</code></a> 和 <a href="https://cn.vuejs.org/api/reactivity-advanced.html#shallowreactive" target="_blank" rel="nofollow"><code>shallowReactive()</code></a> 来绕开深度响应。浅层式 <code>API</code> 创建的状态只在其顶层是响应式的,对所有深层的对象不会做任何处理,避免了对每一个内部属性做响应式所带来的性能成本,这使得属性的访问变得更快,可提升性能。</p>
</blockquote>
<h2>7.2.【readonly 与 shallowReadonly】</h2>
<h3><strong><code>readonly</code></strong></h3>
<ol>
<li><p>作用:用于创建一个对象的深只读副本。</p></li>
<li><p>用法:</p> <pre><code class="language-js">const original = reactive({ ... });
const readOnlyCopy = readonly(original);</code></pre></li>
<li><p>特点:</p>
<ul>
<li>对象的所有嵌套属性都将变为只读。</li>
<li>任何尝试修改这个对象的操作都会被阻止(在开发模式下,还会在控制台中发出警告)。</li>
</ul></li>
<li><p>应用场景:</p>
<ul>
<li>创建不可变的状态快照。</li>
<li>保护全局状态或配置不被修改。</li>
</ul></li>
</ol>
<h3><strong><code>shallowReadonly</code></strong></h3>
<ol>
<li><p>作用:与 <code>readonly</code> 类似,但只作用于对象的顶层属性。</p></li>
<li><p>用法:</p> <pre><code class="language-js">const original = reactive({ ... });
const shallowReadOnlyCopy = shallowReadonly(original);</code></pre></li>
<li><p>特点:</p>
<ul>
<li><p>只将对象的顶层属性设置为只读,对象内部的嵌套属性仍然是可变的。</p></li>
<li><p>适用于只需保护对象顶层属性的场景。</p></li>
</ul></li>
</ol>
<h2>7.3.【toRaw 与 markRaw】</h2>
<h3><code>toRaw</code></h3>
<ol>
<li><p>作用:用于获取一个响应式对象的原始对象, <code>toRaw</code> 返回的对象不再是响应式的,不会触发视图更新。</p>
<blockquote>
<p>官网描述:这是一个可以用于临时读取而不引起代理访问/跟踪开销,或是写入而不触发更改的特殊方法。不建议保存对原始对象的持久引用,请谨慎使用。</p>
<p>何时使用? ------ 在需要将响应式对象传递给非 <code>Vue</code> 的库或外部系统时,使用 <code>toRaw</code> 可以确保它们收到的是普通对象</p>
</blockquote></li>
<li><p>具体编码:</p> <pre><code class="language-js">import { reactive,toRaw,markRaw,isReactive } from "vue";
/* toRaw */
// 响应式对象
let person = reactive({name:'tony',age:18})
// 原始对象
let rawPerson = toRaw(person)
/* markRaw */
let citysd = markRaw([
{id:'asdda01',name:'北京'},
{id:'asdda02',name:'上海'},
{id:'asdda03',name:'天津'},
{id:'asdda04',name:'重庆'}
])
// 根据原始对象citys去创建响应式对象citys2 ------ 创建失败,因为citys被markRaw标记了
let citys2 = reactive(citys)
console.log(isReactive(person))
console.log(isReactive(rawPerson))
console.log(isReactive(citys))
console.log(isReactive(citys2))</code></pre></li>
</ol>
<h3><code>markRaw</code></h3>
<ol>
<li><p>作用:标记一个对象,使其<strong>永远不会</strong>变成响应式的。</p>
<blockquote>
<p>例如使用<code>mockjs</code>时,为了防止误把<code>mockjs</code>变为响应式对象,可以使用 <code>markRaw</code> 去标记<code>mockjs</code></p>
</blockquote></li>
<li><p>编码:</p> <pre><code class="language-js">/* markRaw */
let citys = markRaw([
{id:'asdda01',name:'北京'},
{id:'asdda02',name:'上海'},
{id:'asdda03',name:'天津'},
{id:'asdda04',name:'重庆'}
])
// 根据原始对象citys去创建响应式对象citys2 ------ 创建失败,因为citys被markRaw标记了
let citys2 = reactive(citys)</code></pre></li>
</ol>
<h2>7.4.【customRef】</h2>
<p>作用:创建一个自定义的<code>ref</code>,并对其依赖项跟踪和更新触发进行逻辑控制。</p>
<p>实现防抖效果(<code>useSumRef.ts</code>):</p>
<pre><code class="language-typescript">import {customRef } from "vue";
export default function(initValue:string,delay:number){
let msg = customRef((track,trigger)=>{
let timer:number
return {
get(){
track() // 告诉Vue数据msg很重要,要对msg持续关注,一旦变化就更新
return initValue
},
set(value){
clearTimeout(timer)
timer = setTimeout(() => {
initValue = value
trigger() //通知Vue数据msg变化了
}, delay);
}
}
})
return {msg}
}</code></pre>
<p>组件中使用:</p>
<h1>8. Vue3新组件</h1>
<h2>8.1. 【Teleport】</h2>
<ul>
<li>什么是Teleport?------ Teleport 是一种能够将我们的<strong>组件html结构</strong>移动到指定位置的技术。</li>
</ul>
<pre><code class="language-html"><teleport to='body' >
<div class="modal" v-show="isShow">
<h2>我是一个弹窗</h2>
<p>我是弹窗中的一些内容</p>
<button @click="isShow = false">关闭弹窗</button>
</div>
</teleport></code></pre>
<h2>8.2. 【Suspense】</h2>
<ul>
<li>等待异步组件时渲染一些额外内容,让应用有更好的用户体验</li>
<li>使用步骤:
<ul>
<li>异步引入组件</li>
<li>使用<code>Suspense</code>包裹组件,并配置好<code>default</code> 与 <code>fallback</code></li>
</ul></li>
</ul>
<pre><code class="language-tsx">import { defineAsyncComponent,Suspense } from "vue";
const Child = defineAsyncComponent(()=>import('./Child.vue'))</code></pre>
<pre><code class="language-vue"><template>
<div class="app">
<h3>我是App组件</h3>
<Suspense>
<template v-slot:default>
<Child/>
</template>
<template v-slot:fallback>
<h3>加载中.......</h3>
</template>
</Suspense>
</div>
</template></code></pre>
<h2>8.3.【全局API转移到应用对象】</h2>
<ul>
<li><code>app.component</code></li>
<li><code>app.config</code></li>
<li><code>app.directive</code></li>
<li><code>app.mount</code></li>
<li><code>app.unmount</code></li>
<li><code>app.use</code></li>
</ul>
<h2>8.4.【其他】</h2>
<ul>
<li><p>过渡类名 <code>v-enter</code> 修改为 <code>v-enter-from</code>、过渡类名 <code>v-leave</code> 修改为 <code>v-leave-from</code>。</p></li>
<li><p><code>keyCode</code> 作为 <code>v-on</code> 修饰符的支持。</p></li>
<li><p><code>v-model</code> 指令在组件上的使用已经被重新设计,替换掉了 <code>v-bind.sync。</code></p></li>
<li><p><code>v-if</code> 和 <code>v-for</code> 在同一个元素身上使用时的优先级发生了变化。</p></li>
<li><p>移除了<code>$on</code>、<code>$off</code> 和 <code>$once</code> 实例方法。</p></li>
<li><p>移除了过滤器 <code>filter</code>。</p></li>
<li><p>移除了<code>$children</code> 实例 <code>propert</code>。</p> <p>......</p></li>
</ul>
</article>
````