齐爷学vue3
一、Vue3入门
vite:前端构架工具,构建速度快于webpack。轻量快速、对TS,JSX,CSS开箱即用、按需编译。
创建Vue3工程
1.在想要创建Vue3的位置打开cmd,执行如下命令。
npm create vue@latest
2.功能只选择TypeScript即可。
3.打开项目,执行npm i 安装所有需要的依赖。
npm i
4.运行项目,ctrl c停止项目的运行
npm run dev
vite项目中,index.html是入口文件,且在项目的最外层。
加载index.html
后,Vite
解析 <script type="module" src="xxx">
指向的JavaScript
。
Vue3
中是通过 createApp
函数创建一个应用实例。
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
src中的文件
main.ts
import {createApp} from 'vue' //引入createApp用于创建应用
import App from './App.vue' //引入App根组件
createApp(App).mount('#app')
App.vue
<template>
<div class="app">
<h1>你好啊!</h1>
</div>
</template>
<script lang="ts">
export default {
name:'App' //组件名
}
</script>
<style>
.app{
background-color: aqua;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
实现一个简单的效果
这个例子证明了vue2的语法仍可以在vue3中使用。
src/components/Person.vue
<template>
<div class="person">
<h1>你好啊!</h1>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="showTel">展示联系方式</button>
</div>
</template>
<script lang="ts">
export default {
name:'Person',
data(){
return{
name:'张三',
age:18,
tel:'13888888888'
}
},
methods:{
showTel(){
alert(this.tel)
},
changeName(){
this.name = 'zhang-san'
},
changeAge(){
this.age += 1
}
}
}
</script>
<style scoped>
.person{
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
App.vue
<template>
<div class="app">
<h1>你好啊!</h1>
<Person/>
</div>
</template>
<script lang="ts">
import Person from './components/Person.vue'
export default {
name:'App', //组件名
components:{Person} //注册组件
}
</script>
<style>
.app{
background-color: aqua;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
二、Vue3核心语法
1.OptionsAPI与CompositionAPI
Vue2是OptionsAPI的。(配置式风格:想要新增或修改一个需求,就需要分别修改data,method,computed等(功能的数据,方法等被拆散了),不便于维护和复用)
Vue3是CompositionAPI的。(组合式风格:将功能集中到一个函数中,代码更加有序,利于维护)
2.setup
setup的使用
setup
是Vue3
中一个新的配置项,值是一个函数,它是 Composition API
“表演的舞台”,组件中所用到的:数据、方法、计算属性、监视......等等,均配置在setup
中。
特点如下:
setup
函数返回的对象中的内容,可直接在模板中使用。setup
中访问this
是undefined
。setup
函数会在beforeCreate
之前调用,它是“领先”所有钩子执行的。
<template>
<div class="person">
<h1>你好啊!</h1>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="showTel">展示联系方式</button>
</div>
</template>
<script lang="ts">
export default {
name:'Person',
setup(){ //setup函数中的this是undefined,Vue3已经弱化this了
//数据
let name = '张三' //注意:此时的name,age和tel都不是响应式的
let age = 18
let tel = '13888888888'
//方法
function changeName(){
name = 'zhang-san' //注意,这样修改页面是不会变化的,因为name和age不是响应式的
}
function changeAge(){
age+=1
}
function showTel(){
alert(tel)
}
return {name,age,changeName,changeAge,showTel} //此处是简写形式:正常应为{name:name,age:age......}
}
}
</script>
<style scoped>...
setup的返回值也可以是一个渲染函数(返回的结果会渲染到页面上)
return () => '哈哈'
setup与optionsAPI
vue2的语法可以与vue3的语法共存。
vue2(data,methods等)可以使用vue3语法(setup等)中的内容,但是vue3不能使用vue2语法中的内容。
<template>
<div class="person">
<h1>你好啊!</h1>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="showTel">展示联系方式</button>
<hr>
<h2>测试:{{ a }}</h2>
<h2>测试:{{ c }}</h2>
<button @click="b">测试b</button>
</div>
</template>
<script lang="ts">
export default {
name:'Person',
setup(){ //setup函数中的this是undefined,Vue3已经弱化this了
//数据
let name = '张三' //注意:此时的name,age和tel都不是响应式的
let age = 18
let tel = '13888888888'
//方法
function changeName(){
name = 'zhang-san' //注意,这样修改页面是不会变化的,因为name和age不是响应式的
}
function changeAge(){
age+=1
}
function showTel(){
alert(tel)
}
return {name,age,changeName,changeAge,showTel} //此处是简写形式:正常应为{name:name,age:age......}
},
data(){
return {
a:100,
c:this.name
}
},
methods:{
b(){
console.log("b");
}
}
}
</script>
<style scoped>...
setup的语法糖(简单写法)
将数据写到另一个script中,要标注lang="ts"和setup
<template>
<div class="person">
<h1>你好啊!</h1>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<h2>地址:{{ address }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="showTel">展示联系方式</button>
</div>
</template>
<script lang="ts">
export default {
name:'Person',
}
</script>
<script lang="ts" setup>
//数据
let name = '张三' //相当于在setup中写了name并且return了
let age = 18
let tel = '13888888888'
let address = '辽宁沈阳'
//方法
function changeName(){//相当于在setup中写了changeName()并且return了
name = 'zhang-san'
}
function changeAge(){
age+=1
}
function showTel(){
alert(tel)
}
</script>
<style scoped>...
进一步精简
1.将给组件命名的script合并到setup的script上,需要如下插件。
npm i vite-plugin-vue-setup-extend -D
2.在vite.config.ts中引入插件
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import VueSetupExtend from 'vite-plugin-vue-setup-extend' //引入插件
// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
vueDevTools(),
VueSetupExtend() //追加调用
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
})
3.在script上添加一个属性name=""即可指定组件名
<template>...
<div class="person">
<h1>你好啊!</h1>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<h2>地址:{{ address }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="showTel">展示联系方式</button>
</div>
</template>
<script lang="ts" setup name="Person">
//数据
let name = '张三' //相当于在setup中写了name并且return了
let age = 18
let tel = '13888888888'
let address = '辽宁沈阳'
//方法
function changeName(){//相当于在setup中写了changeName()并且return了
name = 'zhang-san'
}
function changeAge(){
age+=1
}
function showTel(){
alert(tel)
}
</script>
<style scoped>...
3.响应式数据
vue2中,data中的数据就是响应式的(做了数据代理和数据劫持)。
vue3中,通过ref和reactive来定义响应式数据。
ref创建基本类型的响应式数据
<template>...
<div class="person">
<h1>你好啊!</h1>
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<h2>地址:{{ address }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="showTel">展示联系方式</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref} from 'vue' //引入ref
//数据
let name = ref('张三') //将需要变为响应式的数据用ref()包起来,这里会自动.value
let age = ref(18)
let tel = '13888888888'
let address = '辽宁沈阳'
console.log(name,age,tel,address) //可以发现,此时name和age变为了RefImpl实例对象
//方法
function changeName(){
name.value = 'zhang-san' //操作响应式数据时需要.value
}
function changeAge(){
age.value+=1
}
function showTel(){
alert(tel)
}
</script>
<style scoped>...
reactive创建对象类型的响应式数据(响应式对象)
reactive只能定义对象类型的响应式数据。
<template>
<div class="person">
<h2>汽车信息:一辆{{ car.brand }}车,价值{{ car.price }}万</h2>
<button @click="changePrice">修改价格</button>
<br>
<h2>游戏列表:</h2>
<ul>
<li v-for="game in games" :key="game.id">{{ game.name }}</li>
</ul>
<button @click="changeFirstGame">修改第一个游戏的名字</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {reactive} from 'vue'
//数据
let car = reactive({brand:'奔驰',price:100})
let games = reactive([
{id:'01',name:'原神'},
{id:'02',name:'三国杀'},
{id:'03',name:'王者'}
])
console.log(car) //此时发现car变为了Proxy对象,car对象的内容在[[target]]中
function changePrice(){
car.price += 10
}
function changeFirstGame(){
games[0].name = '游戏王'
}
</script>
<style scoped>...
ref创建对象类型的响应式数据(响应式对象)
ref不仅能定义基本类型的响应式数据,还能定义对象类型的响应式数据。
ref在创建对象类型的响应式数据时,底层仍是reactive处理的(RefImpl的value中是一个Proxy)
(template和style和上方代码一样)
<template>...
<div class="person">
<h2>汽车信息:一辆{{ car.brand }}车,价值{{ car.price }}万</h2>
<button @click="changePrice">修改价格</button>
<br>
<h2>游戏列表:</h2>
<ul>
<li v-for="game in games" :key="game.id">{{ game.name }}</li>
</ul>
<button @click="changeFirstGame">修改第一个游戏的名字</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref} from 'vue'
//数据
let car = ref({brand:'奔驰',price:100})
let games = ref([
{id:'01',name:'原神'},
{id:'02',name:'三国杀'},
{id:'03',name:'王者'}
])
function changePrice(){
car.value.price += 10
}
function changeFirstGame(){
games.value[0].name = '游戏王'
}
</script>
<style scoped>...
ref和reactive对比
宏观角度看:
ref
用来定义:基本类型数据、对象类型数据;
reactive
用来定义:对象类型数据。
区别:
ref
创建的变量必须使用.value
(可以使用volar
插件自动添加.value
)。
reactive
重新分配一个新对象,会失去响应式(可以使用Object.assign
去整体替换)。
勾选Dot Value这个拓展就可以自动补充.value
Object.assign整体替换
<template>
<div class="person">
<h2>汽车信息:一辆{{ car.brand }}车,价值{{ car.price }}万</h2>
<button @click="changePrice">修改价格</button>
<button @click="changeBrand">修改品牌</button>
<button @click="changeCar">修改汽车</button>
<hr>
<h2>当前求和为:{{ sum }}</h2>
<button @click="changeSum">点我sum+1</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,reactive} from 'vue'
//数据
let car = reactive({brand:'奔驰',price:100})
let sum = ref(0)
function changePrice(){
car.price += 10
}
function changeBrand(){
car.brand = '宝马'
}
function changeCar(){
Object.assign(car,{brand:'奥迪',price:100}) //重新分配一个新对象的正确方式,Object.assign的作用是将第二个参数的值赋给第一个参数
}
function changeSum(){
sum.value += 1
}
</script>
<style scoped>...
<template>...
<script lang="ts" setup name="Person">
import {ref,reactive} from 'vue'
//数据
let car = ref({brand:'奔驰',price:100})
let sum = ref(0)
function changePrice(){
car.value.price += 10
}
function changeBrand(){
car.value.brand = '宝马'
}
function changeCar(){
car.value = {brand:'奥迪',price:100} //ref就可以直接修改整体对象
}
function changeSum(){
sum.value += 1
}
</script>
<style scoped>...
使用原则(不必过于纠结):
若需要一个基本类型的响应式数据,必须使用
ref
。若需要一个响应式对象,层级不深,
ref
、reactive
都可以。若需要一个响应式对象,且层级较深,推荐使用
reactive
。
toRefs和toRef
toRefs():将一个响应式对象中的每一个属性,转换为ref
对象。
toRef():toRefs
与toRef
功能一致,但toRefs
可以批量转换。
<template>
<div class="person">
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {reactive,toRefs,toRef} from 'vue'
//数据
let person = reactive({
name:'张三',
age:18
})
let {name,age} = toRefs(person) //解构赋值,toRefs():把一个reactive对象变为一个个的ref
let nl = toRef(person,'age') //toRef()只能取出一个属性变为ref
//方法
function changeName(){
name.value += '~'
}
function changeAge(){
age.value += 1
}
</script>
<style scoped>...
4.计算属性computed
计算属性有缓存,如果计算属性中用到的变量没变化,那么计算属性不会计算,而是会使用上一次计算出的结果。
<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 lang="ts" setup name="Person">
import {ref,computed} from 'vue'
let firstName =ref('qi')
let lastName =ref('ye')
//这么定义的fullName是一个只读的计算属性
// let fullName = computed(()=>{
// return firstName.value.slice(0,1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
// })
let fullName = computed({//这么定义的fullName才可以修改
get(){//读fullName时调用
return firstName.value.slice(0,1).toUpperCase() + firstName.value.slice(1) + '-' + lastName.value
},
set(val){//写fullName时调用,这个val就是changeFullName()方法要修改为的li-si
const [str1,str2] = val.split('-')
firstName.value = str1
lastName.value = str2
}
})
function changeFullName(){//引起了fullName的setter调用
console.log(fullName.value);//fullName是一个Ref(ComputedRefImpl)
fullName.value = 'li-si'
}
</script>
<style scoped>...
5.watch监视
作用:监视数据的变化(和Vue2
中的watch
作用一致)
特点:Vue3
中的watch
只能监视以下四种数据:
ref
定义的数据。
reactive
定义的数据。函数返回一个值(
getter
函数)。一个包含上述内容的数组。
参数:
watch的第一个参数是:被监视的数据
watch的第二个参数是:监视的回调
watch的第三个参数是:配置对象(deep、immediate等等.....)
我们在Vue3
中使用watch
的时候,通常会遇到以下几种情况:
情况一
监视ref
定义的【基本类型】数据:直接写数据名即可,监视的是其value
值的改变。
<template>
<div class="person">
<h1>情况一:监视ref定义的基本类型数据</h1>
<h2>当前求和为{{ sum }}</h2>
<button @click="changeSum">点我sum加一</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,watch} from 'vue'
//数据
let sum = ref(0)
//方法
function changeSum(){
sum.value += 1
}
//监视,参数为监视的东西和回调函数
const stopWatch = watch(sum,(newValue,oldValue)=>{
console.log("sum变化了",newValue,oldValue)
if(newValue >= 10){//sum大于等于10时解除监视(通过watch的返回值)
stopWatch()
}
})
</script>
<style scoped>...
情况二
监视ref
定义的对象类型数据:直接写数据名,监视的是对象的地址值,若想监视对象内部的数据,要手动开启深度监视(deep:true)。
在开启深度监视后,修改监视的对象内部的属性时,oldValue就找不到了,所以此时oldValue也会显示为和newValue同样的值。
<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}
}
//监视
watch(person,(newValue,oldValue)=>{ //此时监视的是对象的地址值,若想监视对象内部属性的变化,需要手动开启深度监视deep:true
console.log("person变化了",newValue,oldValue)
},{deep:true,immediate:true})//immediate意思为在项目启动一开始就调用一次watch的回调函数
</script>
<style scoped>...
情况三
监视reactive
定义的对象类型数据,且此时默认开启了深度监视(无法关闭)。
<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>
</div>
</template>
<script lang="ts" setup name="Person">
import {watch,reactive} from 'vue'
//数据
let person = reactive({
name:'硝基',
age:18
})
//方法
function changeName(){
person.name += '~'
}
function changeAge(){
person.age +=1
}
function changePerson(){
Object.assign(person,{name:"李四",age:90}) //因为是批量修改对象的属性,所以此时对象的地址值是不会发生变化的
}
//监视
watch(person,(newValue,oldValue)=>{ //此时所有的修改都能监视到,但是都无法找到oldValue了,因为地址值没变
console.log("person变化了",newValue,oldValue)
})//此时深度监视是默认开启的
</script>
<style scoped>...
情况四
监视ref
或reactive
定义的对象类型数据中的某个属性,注意点如下:
若该属性值不是对象类型,需要写成函数形式。
若该属性值依然是对象类型,可直接监视,也可写成函数,建议写成函数。
结论:监视的要是对象里的属性,那么最好写函数式,注意点:若是对象监视的是地址值,需要关注对象内部,需要手动开启深度监视。
<template>
<div class="person">
<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 {watch,reactive} 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)=>{ //建议使用的形式:函数形式 + deep:true
console.log('person.car变化了',newValue,oldValue)
},{deep:true})
</script>
<style scoped>...
情况五
监视上述的多个数据(使用数组)
watch(() => [person.car.c1,person.name],(newValue,oldValue)=>{ //监视多个数据
console.log('person变化了',newValue,oldValue)
},{deep:true})
6.watchEffect
watch
对比watchEffect
都能监听响应式数据的变化,不同的是监听数据变化的方式不同
watch
:要明确指出监视的数据
watchEffect
:不用明确指出监视的数据(函数中用到哪些属性,那就监视哪些属性)。
<template>
<div class="person">
<h2>需求:水温达到60℃,或水位达到80cm时,给服务器发送请求</h2>
<h2>当前水温:{{ temp }}℃</h2>
<h2>当前水位:{{ height }}cm</h2>
<button @click="changeTemp">点我水温加10</button>
<button @click="changeHeight">点我水位加10</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,watch,watchEffect} from 'vue'
//数据
let temp = ref(10)
let height = ref(0)
//方法
function changeTemp(){
temp.value += 10
}
function changeHeight(){
height.value += 10
}
//监视watch实现
// watch([temp,height],(value)=>{
// let [newTemp,newHeight] = value //解构赋值,从value中获取最新的temp和height
// if(newTemp >= 60 || newHeight >=80){
// console.log('给服务器发送请求')//console.log模拟发送请求
// }
// })
//watchEffect实现
watchEffect(()=>{
if(temp.value >= 60 || height.value >=80){
console.log('给服务器发送请求')
}
})
</script>
<style scoped>...
7.标签的ref属性
作用:用于注册模板引用。
用在普通
DOM
标签上,获取的是DOM
节点。用在组件标签上,获取的是组件实例对象。
<template>
<div class="person">
<h1>中国</h1>
<h2 ref="title2">辽宁</h2>
<h3>沈阳</h3>
<button @click="showLog">点我输出h2元素</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,defineExpose} from 'vue'
//创建一个title2,用于存储ref标记的内容
let title2 = ref()
function showLog(){
console.log(title2.value)
}
defineExpose({title2})//在父组件获取该组件时,指定能够暴露给父组件的元素
</script>
<style scoped>...
8.TypeScript的接口,泛型,自定义类型
index.ts
//定义一个接口,用于限制Person对象的具体属性
export interface PersonInter {
id:string,
name:string,
age:number
}
//定义一个自定义类型
export type Persons = Array<PersonInter>
Person.vue
<template>
<div class="person">
</div>
</template>
<script lang="ts" setup name="Person">
import {type PersonInter,type Persons} from '../types'
let person:PersonInter = {id:'01',name:'齐爷',age:20} //接口规范
let personList:Persons = [ //泛型约束
{id:'01',name:'齐爷',age:20},
{id:'02',name:'齐爷1',age:21},
{id:'03',name:'齐爷2',age:22}
]
</script>
<style scoped>
9.Props
通过defineProps可以接收父组件传来的数据。
App.vue
<template>
<Person :list="personList"/>
</template>
<script lang="ts" setup name="App">
import Person from './components/Person.vue'
import { reactive } from 'vue';
import {type Persons} from './types'
let personList = reactive<Persons>([
{id:'01',name:'齐爷',age:20},
{id:'02',name:'齐爷1',age:21},
{id:'03',name:'齐爷2',age:22}
])
</script>
Person.vue
<template>
<div class="person">
<ul>
<li v-for="p in list" :key="p.id">{{ p.name }}--{{ p.age }}</li>
</ul>
</div>
</template>
<script lang="ts" setup name="Person">
import { withDefaults } from 'vue';
import {type Persons} from '../types'
//defineProps(['a']) 接收a
//let x = defineProps(['list']) //接收list且保存到x(保存到一个对象中)
//接收list且限制类型
//defineProps<{list:Persons}>()
//接收list 限制类型 限制必要性 指定默认值
withDefaults(defineProps<{list?:Persons}>(),{//list后的?是指如果没传过来限制的类型,那么就不接收
list:()=>[{id:'00',name:'zhangsan',age:18}]//默认值
})
</script>
<style scoped>
10.生命周期
概念:Vue
组件实例在创建时要经历一系列的初始化步骤,在此过程中Vue
会在合适的时机,调用特定的函数,从而让开发者有机会在特定阶段运行自己的代码,这些特定的函数统称为:生命周期钩子
规律:
生命周期整体分为四个阶段,分别是:创建、挂载、更新、销毁,每个阶段都有两个钩子,一前一后。
Vue2
的生命周期
创建阶段:
beforeCreate
、created
挂载阶段:
beforeMount
、mounted
更新阶段:
beforeUpdate
、updated
销毁阶段:
beforeDestroy
、destroyed
Vue3
的生命周期
创建阶段:
setup
挂载阶段:
onBeforeMount
、onMounted
更新阶段:
onBeforeUpdate
、onUpdated
卸载阶段:
onBeforeUnmount
、onUnmounted
常用的钩子:onMounted
(挂载完毕)、onUpdated
(更新完毕)、onBeforeUnmount
(卸载之前)
<template>
<div class="person">
<h2>当前求和为:{{ sum }}</h2>
<button @click="add">点我sum加一</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted} from 'vue'
//数据
let sum = ref(0)
//方法
function add(){
sum.value += 1
}
//创建(setup就是创建)
console.log('创建')
//挂载
onBeforeMount(()=>{
console.log('挂载前')
})
onMounted(()=>{
console.log('挂载完毕')
})
//更新
onBeforeUpdate(()=>{
console.log('更新前')
})
onUpdated(()=>{
console.log('更新完毕')
})
//卸载
onBeforeUnmount(()=>{
console.log('卸载前')
})
onUnmounted(()=>{
console.log('卸载完毕')
})
</script>
<style scoped>...
11.自定义Hooks
什么是hook
?—— 本质是一个函数,把setup
函数中使用的Composition API
进行了封装,类似于vue2.x
中的mixin
。
自定义hook
的优势:复用代码, 让setup
中的逻辑更清楚易懂。
将不同的功能抽取为不同的Hook。
useDog.ts
import {reactive} from 'vue'
import axios from 'axios'
export default function (){
//数据
let dogList = reactive([
'https://images.dog.ceo/breeds/pembroke/n02113023_6383.jpg'
])
//方法
async function getDog(){
try{
let result = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
dogList.push(result.data.message)
}catch(error){
alert(error)
}
}
//向外部提供东西
return {dogList,getDog}
}
useSum.ts
import {ref} from 'vue'
export default function (){
let sum = ref(0)
function add(){
sum.value += 1
}
return {sum,add}
}
Person.vue
<template>
<div class="person">
<h2>当前求和为:{{ sum }}</h2>
<button @click="add">点我sum加一</button>
<hr>
<img v-for="(dog,index) in dogList" :src="dog" :key="index">
<br>
<button @click="getDog">再来一只小狗</button>
</div>
</template>
<script lang="ts" setup name="Person">
import useSum from '../hooks/useSum'
import useDog from '../hooks/useDog'
const {sum,add} = useSum()
const {dogList,getDog} = useDog()
</script>
<style scoped>
三、路由route
1.概述
路由就是一组key-value的对应关系,多个路由需要经过路由器的管理。
实现路由需要满足的:
1.导航区、展示区
2.路由器
3.指定路由规则(什么路径对应什么组件)
4.形成一个个的.vue文件(Class.vue,Student.vue等)
安装路由
npm i vue-router
路由组件通常存放在pages
或 views
文件夹,一般组件通常存放在components
文件夹。
通过点击导航,视觉效果上“消失” 了的路由组件,默认是被卸载掉的,需要的时候再去挂载。
2.基本的切换效果
router/index.ts
//创建一个路由器并暴露出去
import {createRouter,createWebHistory} from 'vue-router' //引入createRouter
import Home from '../components/Home.vue'
import News from '../components/News.vue'
import About from '../components/About.vue'
const router = createRouter({
history:createWebHistory(), //路由器的工作模式
routes:[ //一个个的路由规则
{
path:'/home',
component:Home
},
{
path:'/news',
component:News
},
{
path:'/about',
component:About
},
]
})
export default router //暴露路由器
main.ts
import {createApp} from 'vue' //引入createApp用于创建应用
import App from './App.vue' //引入App根组件
import router from './router' //引入路由器
const app = createApp(App) //创建一个应用
app.use(router) //使用路由器
app.mount('#app') //挂载整个应用到app容器中
App.vue
<template>
<div class="app">
<h2 class="title">Vue路由测试</h2>
<!-- 导航区 -->
<div class="navigate">
<RouterLink to="/home" active-class="xiaozhupeiqi">首页</RouterLink> <!--RouterLink中的to表明了路由跳转的位置-->
<RouterLink to="/news" active-class="xiaozhupeiqi">新闻</RouterLink>
<RouterLink to="/about" active-class="xiaozhupeiqi">关于</RouterLink>
</div>
<!-- 展示区 -->
<div class="main-content">
<RouterView></RouterView> <!-- 路由的位置 -->
</div>
</div>
</template>
<script lang="ts" setup name="App">
import {RouterView,RouterLink} from 'vue-router'
</script>
<style>...
3.路由工作模式
history
模式(一般前台项目使用较多)
优点:
URL
更加美观,不带有#
,更接近传统的网站URL
。缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有
404
错误。const router = createRouter({ history:createWebHistory(), //history模式 /******/ })
hash
模式(一般后台项目使用较多)
优点:兼容性更好,因为不需要服务器端处理路径。
缺点:
URL
带有#
不太美观,且在SEO
优化方面相对较差。const router = createRouter({ history:createWebHashHistory(), //hash模式 /******/ })
4.to的两种写法
<!-- 第一种:to的字符串写法 -->
<router-link active-class="active" to="/home">主页</router-link>
<!-- 第二种:to的对象写法 -->
<router-link active-class="active" :to="{path:'/home'}">Home</router-link>
5.命名路由
在创建路由器时,我们可以给路由规则命名。
const router = createRouter({
history:createWebHistory(), //路由器的工作模式
routes:[ //一个个的路由规则
{
name:'zhuye',
path:'/home',
component:Home
},
{
name:'xinwen',
path:'/news',
component:News
},
{
name:'guanyu',
path:'/about',
component:About
},
]
})
在App.vue中就可以通过名字来表名跳转的位置(to的对象写法)。
<RouterLink :to="{name:'xinwen'}" active-class="xiaozhupeiqi">新闻</RouterLink>
6.嵌套路由
路由可以嵌套,在定义路由时使用children数组来定义子路由。
router/index.ts
//创建一个路由器并暴露出去
import {createRouter,createWebHistory} from 'vue-router' //引入createRouter
import Home from '../pages/Home.vue'
import News from '../pages/News.vue'
import About from '../pages/About.vue'
import Detail from '../pages/Detail.vue'
const router = createRouter({
history:createWebHistory(), //路由器的工作模式
routes:[ //一个个的路由规则
{
name:'zhuye',
path:'/home',
component:Home
},
{
name:'xinwen',
path:'/news',
component:News,
children:[//嵌套
{
path:'detail',
component:Detail
}
]
},
{
name:'guanyu',
path:'/about',
component:About
},
]
})
export default router //暴露路由器
在news中展示子路由
<template>
<div class="news">
<!-- news的导航区 -->
<ul>
<li v-for="news in newsList" :key="news.id">
<RouterLink to="/news/detail?">{{ news.title }}</RouterLink>
</li>
</ul>
<!-- news的展示区 -->
<div class="news-content">
<RouterView></RouterView>
</div>
</div>
</template>
<script setup lang="ts" name="News">
import {reactive} from 'vue'
const newsList = reactive([
{id:'01',title:'曼波1',content:'曼波花'},
{id:'01',title:'曼波2',content:'曼波花2'},
{id:'01',title:'曼波3',content:'曼波花3'},
{id:'01',title:'曼波4',content:'曼波花4'},
])
</script>
<style scoped>...
7.路由参数
query
News.vue
<template>
<div class="news">
<!-- news的导航区 -->
<ul>
<li v-for="news in newsList" :key="news.id">
<!-- 第一种写法 ?key=value&key=value... -->
<!-- <RouterLink :to="`/news/detail?id=${news.id}&title=${news.title}&content=${news.content}`">{{ news.title }}</RouterLink> -->
<!-- 第二种写法 query对象 -->
<RouterLink :to="{
name:'detail',
query:{
id:news.id,
title:news.title,
content:news.content
}
}">{{ news.title }}</RouterLink>
</li>
</ul>
<!-- news的展示区 -->
<div class="news-content">
<RouterView></RouterView>
</div>
</div>
</template>
<script setup lang="ts" name="News">
import {reactive} from 'vue'
const newsList = reactive([
{id:'01',title:'曼波1',content:'曼波花'},
{id:'02',title:'曼波2',content:'曼波花2'},
{id:'03',title:'曼波3',content:'曼波花3'},
{id:'04',title:'曼波4',content:'曼波花4'},
])
</script>
<style scoped>...
Detail.vue
<template>
<ul class="news-list">
<li>编号:{{ query.id }}</li>
<li>标题:{{ query.title }}</li>
<li>内容:{{ query.content }}</li>
</ul>
</template>
<script setup lang="ts" name="About">
import { useRoute } from 'vue-router'
import {toRefs} from 'vue'
let route = useRoute()
let {query} = toRefs(route)
</script>
<style scoped>
params
在创建路由规则时要提前占位
routes:[ //一个个的路由规则
{
name:'zhuye',
path:'/home',
component:Home
},
{
name:'xinwen',
path:'/news',
component:News,
children:[
{
name:'detail',
path:'detail/:id/:title/:content', //占位
component:Detail
}
]
},
{
name:'guanyu',
path:'/about',
component:About
},
]
})
写法二中只能写name,不能写path
<template>
<div class="news">
<!-- news的导航区 -->
<ul>
<li v-for="news in newsList" :key="news.id">
<!-- 写法一 -->
<!-- <RouterLink :to="`/news/detail/${news.id}/${news.title}/${news.content}`">{{ news.title }}</RouterLink> -->
<!-- 写法二 -->
<RouterLink :to="{
name:'detail',
params:{
id:news.id,
title:news.title,
content:news.content
}
}">{{ news.title }}</RouterLink>
</li>
</ul>
<!-- news的展示区 -->
<div class="news-content">
<RouterView></RouterView>
</div>
</div>
</template>
<script setup lang="ts" name="News">
import {reactive} from 'vue'
const newsList = reactive([
{id:'01',title:'曼波1',content:'曼波花'},
{id:'02',title:'曼波2',content:'曼波花2'},
{id:'03',title:'曼波3',content:'曼波花3'},
{id:'04',title:'曼波4',content:'曼波花4'},
])
</script>
<style scoped>...
Detail.vue
<template>
<ul class="news-list">
<li>编号:{{ route.params.id }}</li>
<li>标题:{{ route.params.title }}</li>
<li>内容:{{ route.params.content }}</li>
</ul>
</template>
<script setup lang="ts" name="About">
import { useRoute } from 'vue-router';
const route = useRoute()
</script>
<style scoped>
8.路由的props配置
作用:让路由组件更方便的收到参数(可以将路由参数作为props
传给组件)
props的三种写法
routes:[ //一个个的路由规则
{
name:'zhuye',
path:'/home',
component:Home
},
{
name:'xinwen',
path:'/news',
component:News,
children:[
{
name:'detail',
path:'detail/:id/:title/:content',
component:Detail,
//第一种写法:(params时使用的)把路由收到的所有params参数作为props传给路由组件
//props:true
//第二种写法:函数写法(query时使用的)可以自己决定将什么作为props给路由组件,参数就是路由
props(route){
return route.query
}
//第三种写法,对象写法
// props:{
// a:100,
// b:200
// }
}
]
},
{
name:'guanyu',
path:'/about',
component:About
},
]
在Detail.vue中就可以使用defineProps接收了
<template>
<ul class="news-list">
<li>编号:{{ id }}</li>
<li>标题:{{ title }}</li>
<li>内容:{{ content }}</li>
</ul>
</template>
<script setup lang="ts" name="About">
defineProps(['id','title','content'])
</script>
<style scoped>
9.replace属性
作用:控制路由跳转时操作浏览器历史记录的模式
浏览器的历史记录有两种写入方式:分别为push
和replace
:
push
是追加历史记录(默认值)。
replace
是替换当前记录。
开启replace
模式:
跳转到开启了replace的路由后,就无法回到之前的页面了。
<RouterLink replace .......>News</RouterLink>
10.编程式路由导航
编程式路由导航:脱离<RouterLink>实现路由跳转。
Home.vue
实现在首页三秒后跳转到新闻。
<script setup lang="ts" name="Home">
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter()
onMounted(()=>{
setTimeout(()=>{
//在此处编写代码,让路由实现跳转,就需要编程式路由导航
router.push('/news')
},3000)
})
</script>
实现按按钮也能查看新闻
<template>
<div class="news">
<!-- news的导航区 -->
<ul>
<li v-for="news in newsList" :key="news.id">
<button @click="showNewsDetail(news)">查看新闻</button>
<RouterLink :to="{
name:'detail',
params:{
id:news.id,
title:news.title,
content:news.content
}
}">{{ news.title }}</RouterLink>
</li>
</ul>
<!-- news的展示区 -->
<div class="news-content">
<RouterView></RouterView>
</div>
</div>
</template>
<script setup lang="ts" name="News">
import {reactive} from 'vue'
import { useRouter } from 'vue-router'
const newsList = reactive([
{id:'01',title:'曼波1',content:'曼波花'},
{id:'02',title:'曼波2',content:'曼波花2'},
{id:'03',title:'曼波3',content:'曼波花3'},
{id:'04',title:'曼波4',content:'曼波花4'},
])
const router = useRouter()
interface NewsInter{
id:string,
title:string,
content:string
}
function showNewsDetail(news:NewsInter){
router.push({
name:'detail',
params:{
id:news.id,
title:news.title,
content:news.content
}
})
}
</script>
<style scoped>...
11.重定向
作用:将特定的路径,重新定向到已有路由。
const router = createRouter({
history:createWebHistory(), //路由器的工作模式
routes:[ //一个个的路由规则
{
name:'zhuye',
path:'/home',
component:Home
},
{
name:'xinwen',
path:'/news',
component:News,
children:[
{
name:'detail',
path:'detail/:id/:title/:content',
component:Detail,
props:true
}
}
]
},
{
name:'guanyu',
path:'/about',
component:About
},
{ //添加这个路由规则实现重定向
path:'/',
redirect:'/home'
}
]
})
四、Pinia
集中式状态(数据)管理库,将多个组件共享的数据放到Pinia中。
官网:Pinia | The intuitive store for Vue.js
1.准备一个效果
App.vue
<template>
<div>
<Count/>
<LoveTalk/>
</div>
</template>
<script lang="ts" setup name="App">
import Count from './component/Count.vue'
import LoveTalk from './component/LoveTalk.vue';
</script>
Count.vue
<template>
<div class="count">
<h2>当前求和为:{{ sum }}</h2>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="add">加</button>
<button @click="minus">减</button>
</div>
</template>
<script lang="ts" setup name="Count">
import { ref } from 'vue';
//数据
let sum = ref(0) //当前求和
let n = ref(1) //用户选择的数字
//方法
function add(){
sum.value += n.value
}
function minus(){
sum.value -= n.value
}
</script>
<style scoped>...
LoveTalk.vue
npm i nanoid
npm i axios
<template>
<div class="talk">
<button @click="getLoveTalk">获取一句话</button>
<ul>
<li v-for="talk in talkList" :key="talk.id">{{ talk.title }}</li>
</ul>
</div>
</template>
<script lang="ts" setup name="LoveTalk">
import { reactive } from 'vue';
import axios from 'axios';
import {nanoid} from 'nanoid';
let talkList = reactive([
{id:'01',title:'那一天的忧郁,忧郁起来'},
{id:'02',title:'那一天的寂寞,寂寞起来'},
{id:'02',title:'那一天的曼波'},
])
//方法
async function getLoveTalk(){
let {data:{content:title}} = await axios.get('http://api.uomg.com/api/rand.qinghua?format=json') //请求数据
let obj = {id:nanoid(),title} //包装成对象
talkList.unshift(obj) //放到数组中
}
</script>
<style scoped>...
2.搭建Pinia环境
npm i pinia
main.ts
import {createApp} from 'vue'
import App from './App.vue'
//1.引入pinia
import { createPinia } from 'pinia'
const app = createApp(App)
//2.创建pinia
const pinia = createPinia()
//3.安装pinia
app.use(pinia)
app.mount('#app')
3.用pinia存储/读取/修改数据
pinia的位置是src下的一个文件夹:store
component/Count.vue
<template>
<div class="count">
<h2>当前求和为:{{ countStore.sum }}</h2>
<h3>在{{ countStore.address }}说{{ countStore.say }}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="add">加</button>
<button @click="minus">减</button>
</div>
</template>
<script lang="ts" setup name="Count">
import { ref } from 'vue';
import {useCountStore} from '../store/count' //引入useCountStore
const countStore = useCountStore() //使用useCountStore,得到保存count相关的store
//数据
let n = ref(1)
//方法
function add(){
//countStore.sum += 1 //第一种修改方式,直接修改
// countStore.$patch({//第二种修改方式,批量修改$patch
// sum:666,
// say:'woo~',
// address:'沈阳'
// })
//第三种修改方式,actions,可以在actions中添加一些限制功能
countStore.increment(n.value)
}
function minus(){
}
</script>
<style scoped>...
store/count.ts
import {defineStore} from 'pinia'
export const useCountStore = defineStore('count',{
//真正存储数据的地方
state(){
return {
sum:6,
say:'曼波',
address:'辽宁'
}
},
//actions里面放置的是一个个的动作函数,用于响应组件中的动作
actions:{
increment(value: number){
console.log('increment被调用了',value)
if(this.sum < 10){
//修改数据(this是当前的store)
this.sum += value
}
}
}
})
component/LoveTalk.vue
<template>
<div class="talk">
<button @click="getLoveTalk">获取一句话</button>
<ul>
<li v-for="talk in talkStore.talkList" :key="talk.id">{{ talk.title }}</li>
</ul>
</div>
</template>
<script lang="ts" setup name="LoveTalk">
import {useTalkStore} from '../store/loveTalk'
const talkStore = useTalkStore()
//方法
function getLoveTalk(){
talkStore.getATalk()
}
</script>
<style scoped>...
loveTalk.ts
import {defineStore} from 'pinia'
import axios from 'axios'
import {nanoid} from 'nanoid'
export const useTalkStore = defineStore('talk',{
//真正存储数据的地方
state(){
return {
talkList :[
{id:'01',title:'那一天的忧郁,忧郁起来'},
{id:'02',title:'那一天的寂寞,寂寞起来'},
{id:'02',title:'那一天的曼波'},
]
}
},
actions:{
async getATalk(){
let {data:{content:title}} = await axios.get('http://api.uomg.com/api/rand.qinghua?format=json') //请求数据
let obj = {id:nanoid(),title} //包装成对象
this.talkList.unshift(obj) //放到数组中
}
}
})
4.storeToRefs
storeToRefs只会关注store中的数据,不会对方法进行ref包裹。
<template>
<div class="count">
<h2>当前求和为:{{ sum }}</h2>
<h3>在{{ address }}说{{ say }}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="add">加</button>
<button @click="minus">减</button>
</div>
</template>
<script lang="ts" setup name="Count">
import { ref } from 'vue';
import {useCountStore} from '../store/count'
import {storeToRefs} from 'pinia'
const countStore = useCountStore()
const {sum,say,address} = storeToRefs(countStore) //使用storeToRefs来解构赋值
//数据
let n = ref(1)
//方法
function add(){
countStore.increment(n.value)
}
function minus(){
countStore.sum -= n.value
}
</script>
<style scoped>...
<template>
<div class="talk">
<button @click="getLoveTalk">获取一句话</button>
<ul>
<li v-for="talk in talkList" :key="talk.id">{{ talk.title }}</li>
</ul>
</div>
</template>
<script lang="ts" setup name="LoveTalk">
import {useTalkStore} from '../store/loveTalk'
import {storeToRefs} from 'pinia'
const talkStore = useTalkStore()
const {talkList} = storeToRefs(talkStore)
//方法
function getLoveTalk(){
talkStore.getATalk()
}
</script>
<style scoped>...
5.getters
可以对数据加工。
import {defineStore} from 'pinia'
export const useCountStore = defineStore('count',{
//真正存储数据的地方
state(){
return {
sum:1,
say:'曼波',
address:'辽宁'
}
},
actions:{
increment(value: number){
console.log('increment被调用了',value)
if(this.sum < 10){
this.sum += value
}
}
},
getters:{
bigSum(state){ //sum放大10倍
return state.sum * 10
}
}
})
<template>
<div class="count">
<h2>当前求和为:{{ sum }},放大十倍为{{ bigSum }}</h2>
<h3>在{{ address }}说{{ say }}</h3>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="add">加</button>
<button @click="minus">减</button>
</div>
</template>
<script lang="ts" setup name="Count">
import { ref } from 'vue';
import {useCountStore} from '../store/count'
import {storeToRefs} from 'pinia'
const countStore = useCountStore()
const {sum,say,address,bigSum} = storeToRefs(countStore)
//数据
let n = ref(1)
//方法
function add(){
countStore.increment(n.value)
}
function minus(){
countStore.sum -= n.value
}
</script>
<style scoped>
6.$subscribe
通过 store 的 $subscribe()
方法侦听 state
及其变化,可以实现数据不丢失。
talkStore.$subscribe((mutate,state)=>{
console.log('LoveTalk',mutate,state)
localStorage.setItem('talk',JSON.stringify(talkList.value))
})
7.store组合式写法
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}
})
五、组件通信
1.props
概述:props
是使用频率最高的一种通信方式,常用与 :父 ↔ 子。
若 父传子:属性值是非函数。
若 子传父:属性值是函数。
父组件:
<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>
子组件
<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>
2.自定义事件
$event:事件对象。
概述:自定义事件常用于:子 => 父。
<!--在父组件中,给子组件绑定自定义事件:-->
<Child @send-toy="toy = $event"/>
<!--注意区分原生事件与自定义事件中的$event-->
<button @click="toy = $event">测试</button>
//子组件中,触发事件:
this.$emit('send-toy', 具体数据)
3.mitt
概述:与消息订阅与发布(pubsub
)功能类似,可以实现任意组件间通信。
安装mitt
npm i mitt
新建文件:src\utils\emitter.ts
// 引入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
接收数据的组件中:绑定事件、同时在销毁前解绑事件:
import emitter from "@/utils/emitter";
import { onUnmounted } from "vue";
// 绑定事件
emitter.on('send-toy',(value)=>{
console.log('send-toy事件被触发',value)
})
onUnmounted(()=>{
// 解绑事件
emitter.off('send-toy')
})
【第三步】:提供数据的组件,在合适的时候触发事件
import emitter from "@/utils/emitter";
function sendToy(){
// 触发事件
emitter.emit('send-toy',toy.value)
}
注意这个重要的内置关系,总线依赖着这个内置关系
4.v-model
概述:实现 父↔子 之间相互通信。
前序知识 —— v-model
的本质
<!-- 使用v-model指令 -->
<input type="text" v-model="userName">
<!-- v-model的本质是下面这行代码 -->
<input
type="text"
:value="userName"
@input="userName =(<HTMLInputElement>$event.target).value"
>
组件标签上的v-model
的本质::moldeValue
+ update:modelValue
事件。
<!-- 组件标签上使用v-model指令 -->
<AtguiguInput v-model="userName"/>
<!-- 组件标签上v-model的本质 -->
<AtguiguInput :modelValue="userName" @update:model-value="userName = $event"/>
AtguiguInput
组件中:
<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>
<script setup lang="ts" name="AtguiguInput">
// 接收props
defineProps(['modelValue'])
// 声明事件
const emit = defineEmits(['update:model-value'])
</script>
也可以更换value
,例如改成abc
<!-- 也可以更换value,例如改成abc-->
<AtguiguInput v-model:abc="userName"/>
<!-- 上面代码的本质如下 -->
<AtguiguInput :abc="userName" @update:abc="userName = $event"/>
AtguiguInput
组件中:
<template>
<div class="box">
<input
type="text"
:value="abc"
@input="emit('update:abc',$event.target.value)"
>
</div>
</template>
<script setup lang="ts" name="AtguiguInput">
// 接收props
defineProps(['abc'])
// 声明事件
const emit = defineEmits(['update:abc'])
</script>
如果value
可以更换,那么就可以在组件标签上多次使用v-model
<AtguiguInput v-model:abc="userName" v-model:xyz="password"/>
5.$attrs
defineProps未接收的数据,会放到$attrs中。
概述:$attrs
用于实现当前组件的父组件,向当前组件的子组件通信(祖→孙)。
具体说明:$attrs
是一个对象,包含所有父组件传入的标签属性。
注意:
$attrs
会自动排除props
中声明的属性(可以认为声明过的props
被子组件自己“消费”了)
父组件:
<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>
子组件:
<template>
<div class="child">
<h3>子组件</h3>
<GrandChild v-bind="$attrs"/>
</div>
</template>
<script setup lang="ts" name="Child">
import GrandChild from './GrandChild.vue'
</script>
孙组件:
<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>
6.$refs,$parent
概述:
$refs
用于 :父→子。
$parent
用于:子→父。
原理如下:
属性 | 说明 |
---|---|
$refs |
值为对象,包含所有被ref 属性标识的DOM 元素或组件实例。 |
$parent |
值为对象,当前组件的父组件实例对象。 |
Father.vue
<template>
<div class="father">
<h3>父组件</h3>
<h4>房产:{{ house }}</h4>
<button @click="changeToy">修改Child1的玩具</button>
<button @click="changeComputer">修改Child2的电脑</button>
<button @click="getAllChild($refs)">让所有孩子的书变多</button>
<Child1 ref="c1"/>
<Child2 ref="c2"/>
</div>
</template>
<script setup lang="ts" name="Father">
import Child1 from './Child1.vue'
import Child2 from './Child2.vue'
import { ref,reactive } from "vue";
let c1 = ref()
let c2 = ref()
// 数据
let house = ref(4)
// 方法
function changeToy(){
c1.value.toy = '小猪佩奇'
}
function changeComputer(){
c2.value.computer = '华为'
}
function getAllChild(refs:{[key:string]:any}){
console.log(refs)
for (let key in refs){
refs[key].book += 3
}
}
// 向外部提供数据
defineExpose({house})
</script>
Child.vue
<template>
<div class="child1">
<h3>子组件1</h3>
<h4>玩具:{{ toy }}</h4>
<h4>书籍:{{ book }} 本</h4>
<button @click="minusHouse($parent)">干掉父亲的一套房产</button>
</div>
</template>
<script setup lang="ts" name="Child1">
import { ref } from "vue";
// 数据
let toy = ref('奥特曼')
let book = ref(3)
// 方法
function minusHouse(parent:any){
parent.house -= 1
}
// 把数据交给外部
defineExpose({toy,book})
</script>
<template>
<div class="child2">
<h3>子组件2</h3>
<h4>电脑:{{ computer }}</h4>
<h4>书籍:{{ book }} 本</h4>
</div>
</template>
<script setup lang="ts" name="Child2">
import { ref } from "vue";
// 数据
let computer = ref('联想')
let book = ref(6)
// 把数据交给外部
defineExpose({computer,book})
</script>
7.provide、inject
概述:实现祖孙组件直接通信
具体使用:
在祖先组件中通过provide
配置向后代组件提供数据
在后代组件中通过inject
配置来声明接收数据
具体编码:
【第一步】父组件中,使用provide
提供数据
<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>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref,reactive,provide } from "vue";
// 数据
let money = ref(100)
let car = reactive({
brand:'奔驰',
price:100
})
// 用于更新money的方法
function updateMoney(value:number){
money.value += value
}
// 向后代提供数据
provide('moneyContext',{money,updateMoney})
provide('car',car)
</script>
注意:子组件中不用编写任何东西,是不受到任何打扰的
【第二步】孙组件中使用inject
配置项接受数据。
<template>
<div class="grand-child">
<h3>我是孙组件</h3>
<h4>资产:{{ money }}</h4>
<h4>汽车:{{ car }}</h4>
<button @click="updateMoney(6)">点我修改money</button>
</div>
</template>
<script setup lang="ts" name="GrandChild">
import { inject } from 'vue';
// 注入数据
let {money,updateMoney} = inject('moneyContext',{money:0,updateMoney:(x:number)=>{}})
let car = inject('car',{brand:'未知',price:0})
</script>
8.slot
1. 默认插槽
Category标签中的内容会写到<slot></slot>的位置。
父组件Father.vue中:
<Category title="今日热门游戏">
<ul>
<li v-for="g in games" :key="g.id">{{ g.name }}</li>
</ul>
</Category>
子组件Category.vue中:
<template>
<div class="item">
<h3>{{ title }}</h3>
<!-- 默认插槽 -->
<slot>默认内容</slot>
</div>
</template>
2. 具名插槽
具有名字的插槽就是具名插槽。
父组件中:
<Category title="今日热门游戏">
<template v-slot:s1><!--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>
3.作用域插槽
理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(新闻数据在News
组件中,但使用数据所遍历出来的结构由App
组件决定)
父组件:
<Game v-slot="params"><!-- params就是传递给slot的所有的数据 -->
<!-- <Game v-slot:default="params"> -->
<!-- <Game #default="params"> -->
<ul>
<li v-for="g in params.games" :key="g.id">{{ g.name }}</li>
</ul>
</Game>
子组件Game.vue:
<template>
<div class="category">
<h2>今日游戏榜单</h2>
<slot :games="games" a="哈哈"></slot><!-- 给内置组件slot传递gemes和a -->
</div>
</template>
<script setup lang="ts" name="Category">
import {reactive} from 'vue'
let games = reactive([
{id:'asgdytsa01',name:'英雄联盟'},
{id:'asgdytsa02',name:'王者荣耀'},
{id:'asgdytsa03',name:'红色警戒'},
{id:'asgdytsa04',name:'斗罗大陆'}
])
</script>
六、其他API
1.shallowRef 与 shallowReactive
shallowRef
作用:创建一个响应式数据,但只对顶层属性进行响应式处理。
用法:
import {shallowRef} from 'vue'
let myVar = shallowRef(initialValue);
特点:只跟踪引用值的变化,不关心值内部的属性变化。
shallowReactive
作用:创建一个浅层响应式对象,只会使对象的最顶层属性变成响应式的,对象内部的嵌套属性则不会变成响应式的
用法:
import {shallowReactive} from 'vue'
const myObj = shallowReactive({ ... });
特点:对象的顶层属性是响应式的,但嵌套对象的属性不是。
总结
通过使用 shallowRef() 和 shallowReactive() 来绕开深度响应。浅层式
API
创建的状态只在其顶层是响应式的,对所有深层的对象不会做任何处理,避免了对每一个内部属性做响应式所带来的性能成本,这使得属性的访问变得更快,可提升性能。
2.readonly 与 shallowReadonly
作用:保护数据
readonly
作用:用于创建一个对象的深只读副本。
用法:
需要import readonly
const original = reactive({ ... });
const readOnlyCopy = readonly(original);
特点:
对象的所有嵌套属性都将变为只读。
任何尝试修改这个对象的操作都会被阻止(在开发模式下,还会在控制台中发出警告)。
应用场景:
创建不可变的状态快照。
保护全局状态或配置不被修改。
shallowReadonly
作用:与 readonly
类似,但只作用于对象的顶层属性。
用法:
需要import shallowReadonly
const original = reactive({ ... });
const shallowReadOnlyCopy = shallowReadonly(original);
特点:
只将对象的顶层属性设置为只读,对象内部的嵌套属性仍然是可变的。
适用于只需保护对象顶层属性的场景。
3.toRaw 与 markRaw
raw:未经加工的、原始的
toRaw
作用:用于获取一个响应式对象的原始对象, toRaw
返回的对象不再是响应式的,不会触发视图更新。
官网描述:这是一个可以用于临时读取而不引起代理访问/跟踪开销,或是写入而不触发更改的特殊方法。不建议保存对原始对象的持久引用,请谨慎使用。
何时使用? —— 在需要将响应式对象传递给非
Vue
的库或外部系统时,使用toRaw
可以确保它们收到的是普通对象
markRaw
作用:标记一个对象,使其永远不会变成响应式的。
例如使用
mockjs
时,为了防止误把mockjs
变为响应式对象,可以使用markRaw
去标记mockjs
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))
4.customRef(自定义Ref)
作用:创建一个自定义的ref
,并对其依赖项跟踪和更新触发进行逻辑控制。
实现防抖效果(输入一段时间后才更新)(useSumRef.ts
):
封装成一个hooks
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}
}
七、Vue3新组件
Teleport
teleport:传送门
Teleport 是一种能够将我们的组件html结构移动到指定位置的技术。
teleport to=' '中可以写任意一个存在的位置(#app, .stu等都可以)。
<template>
<button @click="isShow = true">展示弹窗</button>
<teleport to='body'> <!-- 将teleport中的内容塞到body中 -->
<div class="modal" v-show="isShow">
<h2>我是弹窗的标题</h2>
<p>我是弹窗的内容</p>
<button @click="isShow = false">关闭弹窗</button>
</div>
</teleport>
</template>
<script setup lang="ts" name="Modal">
import {ref} from 'vue'
let isShow = ref(false)
</script>
Suspense
等待异步组件时渲染一些额外内容,让应用有更好的用户体验
子组件存在异步任务且要打印时,可以使用Suspense包围。
使用步骤:
异步引入组件
使用Suspense
包裹组件,并配置好default
与 fallback
<template>
<div class="app">
<h2>我是App组件</h2>
<Suspense>
<template v-slot:default>
<Child/>
</template>
</Suspense>
</div>
</template>
<script setup lang="ts" name="App">
import {Suspense} from 'vue'
import Child from './Child.vue'
</script>
<template>
<div class="child">
<h2>我是Child组件</h2>
<h3>当前求和为:{{ sum }}</h3>
</div>
</template>
<script setup lang="ts">
import {ref} from 'vue'
import axios from 'axios'
let sum = ref(0)
let {data:{content}} = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json')
console.log(content)
</script>
全局API转移到应用对象
app.component
app.config
app.directive
app.mount
app.unmount
app.use
其他
过渡类名
v-enter
修改为v-enter-from
、过渡类名v-leave
修改为v-leave-from
。
keyCode
作为v-on
修饰符的支持。v-model
指令在组件上的使用已经被重新设计,替换掉了v-bind.sync。
v-if
和v-for
在同一个元素身上使用时的优先级发生了变化。移除了
$on
、$off
和$once
实例方法。移除了过滤器
filter
。移除了
$children
实例propert
。