Vue3
# Vue3快速上手
Vue3+TS快速上手 (opens new window)
# Vue3简介
- 2020年9月18日,Vue.js发布3.0版本,代号:One Piece(海贼王)
- 耗时2年多、2600+次提交 (opens new window)、30+个RFC (opens new window)、600+次PR (opens new window)、99位贡献者 (opens new window)
- github上的tags地址:https://github.com/vuejs/vue-next/releases/tag/v3.0.0
- Vue3支持vue2的大多数特性
- 更好的支持Typescript
# Vue3带来了什么
1.性能的提升
打包大小减少41%
初次渲染快55%, 更新渲染快133%
内存减少54%
......
2.源码的升级
使用Proxy代替defineProperty实现响应式
重写虚拟DOM的实现和Tree-Shaking
......
3.拥抱TypeScript
- Vue3可以更好的支持TypeScript
4.新的特性
- Composition (组合) API
- setup
- ref 和 reactive
- computed 和 watch
- 新的生命周期函数
- provide与inject
- ...
- 新组件
- Fragment - 文档碎片
- Teleport - 瞬移组件的位置
- Suspense - 异步加载组件的loading界面
- 其它API更新
- 全局API的修改
- 将原来的全局API转移到应用对象
- 模板语法变化
# 一、创建Vue3.0工程
# 使用 vue-cli 创建
官方文档:https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create
## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version
## 安装或者升级你的@vue/cli
npm install -g @vue/cli
## 保证 vue cli 版本在 4.5.0 以上
## 创建
vue create vue_test
## 启动
cd vue_test
npm run serve
2
3
4
5
6
7
8
9
10
然后的步骤
- Please pick a preset - 选择 Manually select features
- Check the features needed for your project - 选择上 TypeScript ,特别注意点空格是选择,点回车是下一步
- Choose a version of Vue.js that you want to start the project with - 选择 3.x (Preview)
- Use class-style component syntax - 直接回车
- Use Babel alongside TypeScript - 直接回车
- Pick a linter / formatter config - 直接回车
- Use history mode for router? - 直接回车
- Pick a linter / formatter config - 直接回车
- Pick additional lint features - 直接回车
- Where do you prefer placing config for Babel, ESLint, etc.? - 直接回车
- Save this as a preset for future projects? - 直接回车
如果忘记了选择typescript需要
npm install --save-dev typescript @types/node @types/vue
npx tsc --init #生成配置文件
2
# 2.使用 vite 创建
官方文档:https://v3.cn.vuejs.org/guide/installation.html#vite
vite官网:https://vitejs.cn
- 什么是vite?—— 新一代前端构建工具。
- 优势如下:
- 开发环境中,无需打包操作,可快速的冷启动。
- 轻量快速的热重载(HMR)。
- 真正的按需编译,不再等待整个应用编译完成。
- 传统构建 与 vite构建对比图
## 创建工程
npm init vite-app <project-name>
## 进入工程目录
cd <project-name>
## 安装依赖
npm install
## 运行
npm run dev
2
3
4
5
6
7
8
- vite 是一个由原生 ESM 驱动的 Web 开发构建工具。在开发环境下基于浏览器原生 ES imports 开发,
- 它做到了本地快速开发启动, 在生产环境下基于 Rollup 打包。
- 快速的冷启动,不需要等待打包操作;
- 即时的热模块更新,替换性能和模块数量的解耦让更新飞起;
- 真正的按需编译,不再等待整个应用编译完成,这是一个巨大的改变。
# 对比
main.js对比
// 引入的不再是Vue构造函数,引入的是一个名为createApp的工厂函数
import { createApp } from 'vue'
import App from './App.vue'
createApp(App).mount('#app')
// vue2
// const vm = new Vue({
// render: h => h(App)
// })
// vm.$mount('#app')
// vue3
// 创建应用实例对象-app(类似于之前vue2中的vm,但app比vm更“轻”)
// const app = createApp(App)
// 挂载
// app.mount('#app')
// 卸载
// app.unmount('#app')
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
App.vue
<template>
<!--Vue3的组件木板结构可以没有根标签-->
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
vue3可以没有根标签
# 安装vue3开发者工具
方式一:
chorme网上商店:https://chrome.google.com/webstore/category/extensions?hl=zh-CN
方式二:离线安装
# 二、常用 Composition API
官方文档: https://v3.cn.vuejs.org/guide/composition-api-introduction.html
# 选项式API和组合式API
Vue 的组件可以按两种不同的风格书写:选项式 API 和组合式 API。
# 选项式 API (Options API) (opens new window)
使用选项式 API,我们可以用包含多个选项的对象来描述组件的逻辑,例如 data
、methods
和 mounted
。选项所定义的属性都会暴露在函数内部的 this
上,它会指向当前的组件实例。
<script>
export default {
// data() 返回的属性将会成为响应式的状态
// 并且暴露在 `this` 上
data() {
return {
count: 0
}
},
// methods 是一些用来更改状态与触发更新的函数
// 它们可以在模板中作为事件处理器绑定
methods: {
increment() {
this.count++
}
},
// 生命周期钩子会在组件生命周期的各个不同阶段被调用
// 例如这个函数就会在组件挂载完成后被调用
mounted() {
console.log(`The initial count is ${this.count}.`)
}
}
</script>
<template>
<button @click="increment">Count is: {{ count }}</button>
</template>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 组合式 API (Composition API) (opens new window)
通过组合式 API,我们可以使用导入的 API 函数来描述组件逻辑。在单文件组件中,组合式 API 通常会与 <script setup>
(opens new window) 搭配使用。这个 setup
attribute 是一个标识,告诉 Vue 需要在编译时进行一些处理,让我们可以更简洁地使用组合式 API。比如,<script setup>
中的导入和顶层变量/函数都能够在模板中直接使用。
下面是使用了组合式 API 与 <script setup>
改造后和上面的模板完全一样的组件:
<script setup>
import { ref, onMounted } from 'vue'
// 响应式状态
const count = ref(0)
// 用来修改状态、触发更新的函数
function increment() {
count.value++
}
// 生命周期钩子
onMounted(() => {
console.log(`The initial count is ${count.value}.`)
})
</script>
<template>
<button @click="increment">Count is: {{ count }}</button>
</template>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# vue3 中 setup 函数、defineComponent 函数 和 script 标签上的 setup
vue3 中 setup 函数、defineComponent 函数 和 script 标签上的 setup (opens new window)
# setup 函数的使用:
<template>
<div>{{ str }}</div>
<div v-for="(item, idx) in list" :key="idx"></div>
<div>{{ obj }}</div>
</template>
<script>
import { ref, reactive, toRefs } from 'vue'
export default {
setup() {
const str = ref('qwert')
const list = ref([])
const obj = reactive({})
return {
str,
list,
...toRefs(obj)
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# defineComponent 函数
defineComponent 函数是 setup 函数的语法糖之一。
defineComponent 函数支持 TypeScript 的参数类型推断(专为 TS 准备的)。若使用的是 ts + vue3,强力推荐使用它。
defineComponent 函数的一般用法
<template>
<div>{{ str }}</div>
<div v-for="(item, idx) in list" :key="idx"></div>
<div>{{ obj }}</div>
</template>
<script>
import { ref, toRefs, reactive, defineComponent } from 'vue'
export default defineComponent({
setup() {
const str = ref('qwert')
const list = ref([])
const obj = reactive({})
return {
str,
list,
...toRefs(obj)
}
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
ts + vue3 中使用 defineComponent 函数
import { defineComponent, PropType} from 'vue';
interface UserInfo = {
id: number,
name: string,
age: number
}
export default defineComponent({
//props需要使用PropType泛型来约束。
props: {
userInfo: {
type: Object as PropType<UserInfo>, // 泛型类型
required: true
}
},
})
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# script setup
标签
<script setup>
标签又称 setup 文件——是 setup 函数的语法糖之一。
setup 文件的特点: 对于在 setup 文件中定义的属性和方法,无需将它们 return 到最后的结果对象中去,直接在 template 模板中使用它们即可。
<template>
<div>{{ str }}</div>
<div v-for="(item, idx) in list" :key="idx"></div>
<div>{{ obj }}</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
const str = ref('qwert')
const list = ref([])
const obj = reactive({})
</script>
2
3
4
5
6
7
8
9
10
11
12
# setup函数
- 理解:Vue3.0中一个新的配置项,值为一个函数。
- setup是所有Composition API(组合API)“ 表演的舞台 ”
- 组件中所用到的:数据、方法等等,均要配置在setup中。
- setup函数的两种返回值:
- 若返回一个对象,则对象中的属性、方法, 在模板中均可以直接使用。(重点关注!)
- 若返回一个渲染函数:则可以自定义渲染内容。
- 注意点:
- 尽量不要与Vue2.x配置混用
- Vue2.x配置(data、methos、computed...)中可以访问到setup中的属性、方法。
- 但在setup中不能访问到Vue2.x配置(data、methos、computed...)。
- 如果有重名, setup优先。
- setup不能是一个async函数,因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性。(后期也可以返回一个Promise实例,但需要Suspense和异步组件的配合)
- 尽量不要与Vue2.x配置混用
setup() 函数是在 beforeCreate 钩子之前执行的一个函数。
setup 接收 2 个参数:
- props:一个响应式的对象,包含了从父组件中传过来的所有属性。不能使用 ES6 解构。
- context:一个普通的对象,暴露了其它可能在 setup 中有用的值。能使用 ES6 解构。
setup 的返回值:
- 一个对象:对象里的属性都可以在模板中使用。
- 当 setup 函数返回一个对象时,该对象里的属性均可在模板中使用。只不过,如果该属性是个对象,在模板里使用该对象时,该对象会被自动浅解包,因此,不应在模板中直接使用 对象.属性名 的形式访问该对象里的属性。
- 一个函数:该函数可以直接使用在同一作用域中声明的响应式状态。
- 一个对象:对象里的属性都可以在模板中使用。
setup 函数的特点:
在 setup 函数中定义的变量和方法,必须将它们 return 到最后的结果对象中去,才能在 template 模板中使用它们。
- 新的option, 所有的组合API函数都在此使用, 只在初始化时执行一次
- 函数如果返回对象, 对象中的属性或方法, 模板中可以直接使用
<template>
<div>
<h1>个人信息</h1>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>{{msg}}</h2>
<button @click="sayHello">点击使用vue3中setup中的方法</button><br/>
<button @click="sayTest">点击使用vue2中methods中的方法</button><br/>
<button @click="test1">vue2定义中可以访问到vue3的数据和方法</button><br/>
<button @click="test2">vue3定义中可以访问不到vue2的数据和方法</button><br/>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'SetUp',
data () {
return {
msg: '我是vue2data里面的数据'
}
},
methods: {
sayTest () {
alert('vue2中的方法')
},
test1 () {
console.log(this.msg)
console.log(this.name)
console.log(this.age)
console.log(this.sayHello)
}
},
setup () {
// 数据
const name = '张三'
const age = 18
// 方法
function sayHello () {
alert(`我是vue3中的方法,我是${name},年龄:${age}`)
}
function test2 () {
console.log(name)
console.log(age)
console.log(sayHello)
// console.log(this.msg) ts会报错
// console.log(this.sayTest)
}
// 返回一个对象(常用)
return {
name,
age,
sayHello,
test2
}
// 返回一个函数(渲染函数)
// return () => {
// return h('h1',"我是渲染函数,我会替换网页的全部内容,重新渲染")
// }
}
})
</script>
<style lang="scss" scoped>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# 细节
setup执行的时机
- 在beforeCreate之前执行(一次), 此时组件对象还没有创建
- this是undefined, 不能通过this来访问data/computed/methods / props
- 其实所有的composition API相关回调函数中也都不可以
setup的返回值
一般都返回一个对象: 为模板提供数据, 也就是模板中可以直接使用此对象中的所有属性/方法
返回对象中的属性会与data函数返回对象的属性合并成为组件对象的属性
返回对象中的方法会与methods中的方法合并成功组件对象的方法
如果有重名, setup优先
注意:
一般不要混合使用: methods中可以访问setup提供的属性和方法, 但在setup方法中不能访问data和methods
setup不能是一个async函数: 因为返回值不再是return的对象, 而是promise, 模板看不到return对象中的属性数据
setup的参数
- props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性。
- context:上下文对象
- attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于
this.$attrs
。 - slots: 收到的插槽内容, 相当于
this.$slots
。 - emit: 分发自定义事件的函数, 相当于
this.$emit
。
- attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于
完整代码
父组件
<template>
<h1>parent, msg: {{msg}}</h1>
<set-up-child :msg="msg" @hello="xxx" msg2="我是msg2, props里面没有,会通过attrs"></set-up-child>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import SetUpChild from './SetUpChild.vue'
export default defineComponent({
components: { SetUpChild },
name: 'SetUpParent',
setup () {
const msg = ref('我是父组件的信息')
function xxx (val: string) {
msg.value += val
}
return {
msg,
xxx
}
}
})
</script>
<style lang="scss" scoped>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
子组件
<template>
<h2>Child子级组件</h2>
<h3>msg:{{ msg }}</h3>
<!-- <h3>count:{{ count }}</h3> -->
<button @click="emitXxx">分发事件</button>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'SetUpChild',
props: ['msg'],
emits: ['hello'],
setup (props, ctx) {
// props参数,是一个对象,里面有父级组件向子级组件传递的数据,并且是在子级组件中使用props接收到的所有的属性
// 包含props配置声明且传入了的所有属性的对象
console.log('props', props)
// context参数,是一个对象,里面有attrs对象(获取当前组件标签上的所有的属性的对象,但是该属性是在props中没有声明接收的所有的尚需经的对象),emit方法(分发事件的),slots对象(插槽)
// 包含没有在props配置中声明的属性的对象, 相当于 this.$attrs
console.log(ctx)
console.log(ctx.attrs.msg2)
// 按钮的点击事件的回调函数
function emitXxx () {
// context.emit('xxx','++')
ctx.emit('hello', '++')
}
return {
emitXxx
}
}
})
</script>
<style lang="scss" scoped>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
app.vue 父组件
<template>
<!--Vue3的组件模板结构可以没有根标签-->
<Demo @hello="hello" :msg="msg">
<!--<span>45454455</span>-->
<template v-slot:abc>
<span> 123456</span>
</template>
</Demo>
</template>
<script>
import Demo from "./components/Demo";
import {ref} from "vue";
export default {
name: 'App',
components: {
Demo
},
setup() {
let msg = ref('父组件的信息')
function hello(value) {
console.log(`父组件的方法执行了,我拿到子组件传递过来的参数${value}`)
}
return {
msg,
hello
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Demo.vue 子组件
<template>
<div>
<h1>姓名:{{data.name}}</h1>
<button @click="test">触发自定义事件(子传父)</button>
</div>
</template>
<script>
import {reactive} from "vue";
export default {
name: 'Demo',
beforeCreate() {
console.log("beforeCreate执行了")
},
props: ['msg'],
emits: ['hello'], // 不接收也不会警告,
setup(props, context) {
console.log("set会在beforeCreate之前执行,并且this为空",this)
console.log(props.msg)
// console.log(context.attrs) // 相当于vue2中的$attrs.父组件传递过来的信息,如果没用props来接收,会在这里拿到。接收了就拿不到了
// console.log(context.emit) // 触发自定义事件
console.log("slots",context.slots)
let data = reactive({
name: "张三"
})
function test() {
console.log("test方法执行了")
context.emit('hello',666)
}
return {
data,
test
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# ref函数
修改数据 要xxx.value = 新值,才能修改比较麻烦
- 作用: 定义一个响应式的数据
- 语法:
const xxx = ref(initValue)
- 创建一个包含响应式数据的引用对象(reference对象,简称ref对象)。
- JS中操作数据:
xxx.value
- 模板中读取数据: 不需要.value,直接:
<div></div>
- 备注:
- 接收的数据可以是:基本类型、也可以是对象类型。
- 基本类型的数据:响应式依然是靠
Object.defineProperty()
的get
与set
完成的。 - 对象类型的数据:内部 “ 求助 ” 了Vue3.0中的一个新函数——
reactive
函数。
<template>
<div>
{{ count }}
<br/>
{{ obj.name }}
<br/>
{{ obj.car.name }}
<br/>
<button @click="update">点我++</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
name: 'RefV',
setup () {
// ref是一个函数,作用:定义一个响应式的数据,返回的是一个Ref对象,对象中有一个value属性,如果需要对数据进行操作,
// 需要使用该Ref对象调用value属性的方式进行数据的操作
const count = ref(1)
const obj = ref({
name: '张三',
car: {
name: '奔驰',
color: 'red'
}
})
console.log(count) // 对象
console.log(obj) // RefImpl对象
console.log(obj.value.car) // Proxy(Object)对象
function update () {
count.value++
obj.value.name += '=='
obj.value.car.name += '=='
}
return {
count,
update,
obj
}
}
})
</script>
<style lang="scss" scoped>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<template>
<div>
<h1>{{name}}</h1>
<h1>{{age}}</h1>
<h1>{{job.type}}</h1>
<h1>{{job.salary}}</h1>
<button @click="changeInfo">更改信息</button>
</div>
</template>
<script>
import {ref} from "vue";
export default {
name: 'Ref',
setup() {
let name = ref('张三')
let age = ref(18)
let job = ref( {
type: "UI设计师",
salary: '18k'
})
function changeInfo() {
name.value = '李四'
age.value = 38
job.value.type="前端工程师"
job.value.salary="45k"
}
return {
name,
age,
job,
changeInfo
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# reactive函数
只能处理对象类型,不能处理基本类型
实例代码麻烦之处在于使用和修改数据都要用person,之后会处理掉 参考toRef,toRefs
- 作用: 定义一个对象类型的响应式数据(基本类型不要用它,要用
ref
函数) - 语法:
const 代理对象= reactive(源对象)
接收一个对象(或数组),返回一个代理对象(Proxy的实例对象,简称proxy对象) - reactive定义的响应式数据是“深层次的”。
- 内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据进行操作。
<template>
<div>
{{ proxy.name }}
<br/>
{{ proxy.car.name }}
<br/>
<button @click="update">点我++</button>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive } from 'vue'
export default defineComponent({
name: 'ReactiveV',
setup () {
/*
reactive
作用: 定义多个数据的响应式
const proxy = reactive(obj): 接收一个普通对象然后返回该普通对象的响应式代理器对象
响应式转换是“深层的”:会影响对象内部所有嵌套的属性
内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据都是响应式的
*/
const obj = {
name: '张三',
car: {
name: '奔驰',
color: 'red'
}
}
const proxy = reactive(obj)
function update () {
proxy.name += '=='
proxy.car.name += '=='
}
// 总结: 如果操作代理对象,目标对象中的数据也会随之变化,
// 同时如果想要在操作数据的时候,界面也要跟着重新更新渲染,那么也是操作代理对象
return {
proxy,
update
}
}
})
</script>
<style lang="scss" scoped>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<template>
<div>
<h1>{{person.name}}</h1>
<h1>{{person.age}}</h1>
<h1>{{person.job.type}}</h1>
<h1>{{person.job.salary}}</h1>
<h1>{{person.a.b.c}}</h1>
<h1>{{person.hobby}}</h1>
<button @click="changeInfo">更改信息</button>
</div>
</template>
<script>
import {reactive} from "vue";
export default {
name: 'Reactive',
setup() {
let person = reactive({
name: '张三',
age: 18,
job:{
type: "UI设计师",
salary: '18k'
},
a:{
b:{
c: 666
}
},
hobby: ['1','2','3']
})
function changeInfo() {
person.name = '李四'
person.age = 38
person.job.type="前端工程师"
person.job.salary="45k"
person.a.b.c = 999
person.hobby[0] = "学习"
}
return {
person,
changeInfo
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Vue3.0中的响应式原理
# vue2.x的响应式
实现原理:
对象类型:通过
Object.defineProperty()
对属性的读取、修改进行拦截(数据劫持)。数组类型:通过重写更新数组的一系列方法来实现拦截。(对数组的变更方法进行了包裹)。
Object.defineProperty(data, 'count', { get () {}, set () {} })
1
2
3
4
存在问题:
- 新增属性、删除属性, 界面不会更新。
- 直接通过下标修改数组, 界面不会自动更新。
# vue2实现原理:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
let person = {
name: "张三",
age:18
}
// vue2 实现响应式原理
let p = {}
// 汇总对象中的所有属性形成一个数组
const keys = Object.keys(person);
keys.forEach((k) => {
Object.defineProperty(p,k,{
configurable: true, // 开启这个才能删除
get() {
return person[k]
},
set(value) {
console.log(`${k}被改变了,我要去解析模板,生成虚拟DOM....`)
person[k] = value
}
})
})
</script>
</body>
</html>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Vue3.0的响应式
- 实现原理:
- 通过Proxy(代理): 拦截对象中任意属性的变化, 包括:属性值的读写、属性的添加、属性的删除等。
- 通过Reflect(反射): 对源对象的属性进行操作。
- MDN文档中描述的Proxy与Reflect:
Proxy:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Reflect:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Reflect
new Proxy(data, { // 拦截读取属性值 get (target, prop) { return Reflect.get(target, prop) }, // 拦截设置属性值或添加新属性 set (target, prop, value) { return Reflect.set(target, prop, value) }, // 拦截删除属性 deleteProperty (target, prop) { return Reflect.deleteProperty(target, prop) } }) proxy.name = 'tom'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
let person = {
name: "张三",
age:18
}
/*
// vue2 实现响应式原理
let p = {}
// 汇总对象中的所有属性形成一个数组
const keys = Object.keys(person);
keys.forEach((k) => {
Object.defineProperty(p,k,{
configurable: true, // 开启这个才能删除
get() {
return person[k]
},
set(value) {
console.log(`${k}被改变了,我要去解析模板,生成虚拟DOM....`)
person[k] = value
}
})
})
*/
// 模拟vue3实现原理
// const p = new Proxy(person,{}) 可以传一个空对象,也可以实现功能,但检测不到,无意义
const p = new Proxy(person, {
// 读取某个属性时调用
get(target, propName) {
console.log(`读取${propName}属性`)
//return target[propName]
return Reflect.get(target, propName)
},
// 修改或追加某个属性时调用
set(target,propName,value){
console.log(`修改或添加${propName}属性,我要去更新dom`)
//target[propName] = value
Reflect.set(target, propName, value)
},
// 删除某个属性调用
deleteProperty(target, propName) {
console.log(`删除${propName}属性,我要去更新dom`)
// return delete target[propName]
return Reflect.deleteProperty(target, propName)
}
})
</script>
</body>
</html>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# reactive对比ref
- 从定义数据角度对比:
- ref用来定义:基本类型数据。
- reactive用来定义:对象(或数组)类型数据。
- 备注:ref也可以用来定义对象(或数组)类型数据, 它内部会自动通过
reactive
转为代理对象。
- 从原理角度对比:
- ref通过
Object.defineProperty()
的get
与set
来实现响应式(数据劫持)。 - reactive通过使用Proxy来实现响应式(数据劫持), 并通过Reflect操作源对象内部的数据。
- ref通过
- 从使用角度对比:
- ref定义的数据:操作数据需要
.value
,读取数据时模板中直接读取不需要.value
。 - reactive定义的数据:操作数据与读取数据:均不需要
.value
。
- ref定义的数据:操作数据需要
<template>
<h2>reactive和ref的细节问题</h2>
<h3>m1:{{ m1 }}</h3>
<h3>m2:{{ m2 }}</h3>
<h3>m3:{{ m3 }}</h3>
<hr />
<button @click="update">更新数据</button>
</template>
<script lang="ts">
import { defineComponent, ref, reactive } from 'vue'
export default defineComponent({
name: 'App',
// 是Vue3的 composition API中2个最重要的响应式API(ref和reactive)
// ref用来处理基本类型数据, reactive用来处理对象(递归深度响应式)
// 如果用ref对象/数组, 内部会自动将对象/数组转换为reactive的代理对象
// ref内部: 通过给value属性添加getter/setter来实现对数据的劫持
// reactive内部: 通过使用Proxy来实现对对象内部所有数据的劫持, 并通过Reflect操作对象内部数据
// ref的数据操作: 在js中要.value, 在模板中不需要(内部解析模板时会自动添加.value)
setup() {
// 通过ref的方式设置的数据
const m1 = ref('abc')
const m2 = reactive({
name: '小明',
wife: {
name: '小红',
},
})
// ref也可以传入对象吗
const m3 = ref({
name: '小明',
wife: {
name: '小红',
},
})
// 更新数据
const update = () => {
// ref中如果放入的是一个对象,那么是经过了reactive的处理,形成了一个Proxy类型的对象
console.log(m3)
m1.value += '==='
m2.wife.name += '==='
// m3.value.name += '==='
m3.value.wife.name += '==='
console.log(m3.value.wife)
}
return {
m1,
m2,
m3,
update,
}
},
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 计算属性与监视
<template>
<div>
<h2>计算属性和监视</h2>
<fieldset>
<legend>姓名操作</legend>
姓氏:<input
type="text"
placeholder="请输入姓氏"
v-model="user.firstName"
/><br />
名字:<input
type="text"
placeholder="请输入名字"
v-model="user.lastName"
/><br />
</fieldset>
<fieldset>
<legend>计算属性和监视的演示</legend>
姓名:<input type="text" placeholder="显示姓名" v-model="fullName1" /><br />
姓名:<input type="text" placeholder="显示姓名" v-model="fullName2" /><br />
姓名:<input type="text" placeholder="显示姓名" v-model="fullName3" /><br />
</fieldset>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, computed, ref, watch, watchEffect } from 'vue'
export default defineComponent({
setup () {
const user = reactive({
firstName: '张',
lastName: '三'
})
// 返回的是一个Ref属性
// const fullName1 = computed(() => {
// return user.firstName + '-' + user.lastName
// })
const fullName1 = computed({
get () {
return user.firstName + '-' + user.lastName
},
set (val: string) {
const names = val.split('-')
user.firstName = names[0]
user.lastName = names[1]
}
})
// 监视----监视指定的数据
// immediate 默认会执行一次watch,deep 深度监视
const fullName2 = ref('')
// watch(user,
// ({ firstName, lastName }) => {
// fullName2.value = firstName + '-' + lastName
// },
// { immediate: true, deep: true }
// )
// 监视,不需要配置immediate,本身默认就会进行监视,(默认执行一次)
const fullName3 = ref('1_3')
// watchEffect(() => {
// fullName3.value = user.firstName + '-' + user.lastName
// })
// 监视fullName3的数据,改变firstName和lastName
watchEffect(() => {
const names = fullName3.value.split('_')
user.firstName = names[0]
user.lastName = names[1]
})
// watch---可以监视多个数据的
watch([user.firstName, user.lastName, fullName3], () => {
// 这里的代码就没有执行,fullName3是响应式的数据,但是,user.firstName,user.lastName不是响应式的数据
console.log('====')
})
// 当我们使用watch监视非响应式的数据的时候,代码需要改一下
watch([() => user.firstName, () => user.lastName, fullName3], () => {
// 这里的代码就没有执行,fullName3是响应式的数据,但是,user.firstName,user.lastName不是响应式的数据
console.log('123====')
})
return {
user,
fullName1,
fullName2,
fullName3
}
}
})
</script>
<style lang="scss" scoped>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# computed函数
与Vue2.x中computed配置功能一致
写法
import {computed} from 'vue' setup(){ ... //计算属性——简写 let fullName = computed(()=>{ return person.firstName + '-' + person.lastName }) //计算属性——完整 let fullName = computed({ get(){ return person.firstName + '-' + person.lastName }, set(value){ const nameArr = value.split('-') person.firstName = nameArr[0] person.lastName = nameArr[1] } }) }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
完整代码:
<template>
<div>
姓:<input type="text" v-model="person.firstName"><br>
名: <input type="text" v-model="person.lastName"><br>
<h1>全名:{{person.fullName}}</h1>
全名: <input type="text" v-model="person.fullName"><br>
</div>
</template>
<script>
import {computed, reactive} from "vue";
export default {
name: 'ComputedCustom',
setup() {
let person = reactive({
firstName: "张",
lastName: "三"
})
// 计算属性(简写形式,没有考虑计算属性被修改的情况)
// person.fullName = computed(() => {
// return person.firstName + person.lastName
// })
// 计算属性,完整写法
person.fullName = computed({
set(value) {
const nameArr = value.split("-")
person.firstName = nameArr[0]
person.lastName = nameArr[1]
},
get() {
return person.firstName +"-" + person.lastName
}
})
return {
person
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# watch函数
与Vue2.x中watch配置功能一致
两个小“坑”:
- 监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)。
- 监视reactive定义的响应式数据中某个属性时:deep配置有效。
//情况一:监视ref定义的响应式数据 watch(sum,(newValue,oldValue)=>{ console.log('sum变化了',newValue,oldValue) },{immediate:true}) //情况二:监视多个ref定义的响应式数据 watch([sum,msg],(newValue,oldValue)=>{ console.log('sum或msg变化了',newValue,oldValue) }) /* 情况三:监视reactive定义的响应式数据 若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue!! 若watch监视的是reactive定义的响应式数据,则强制开启了深度监视 */ watch(person,(newValue,oldValue)=>{ console.log('person变化了',newValue,oldValue) },{immediate:true,deep:false}) //此处的deep配置不再奏效 //情况四:监视reactive定义的响应式数据中的某个属性 watch(()=>person.job,(newValue,oldValue)=>{ console.log('person的job变化了',newValue,oldValue) },{immediate:true,deep:true}) //情况五:监视reactive定义的响应式数据中的某些属性 watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{ console.log('person的job变化了',newValue,oldValue) },{immediate:true,deep:true}) //特殊情况 watch(()=>person.job,(newValue,oldValue)=>{ console.log('person的job变化了',newValue,oldValue) },{deep:true}) //此处由于监视的是reactive素定义的对象中的某个属性,所以deep配置有效
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
完整代码:
<template>
<div>
<h1>sum:{{sum}}</h1>
<button @click="sum++">点击++</button>
<h1>msg:{{msg}}</h1>
<button @click="msg = msg + '1'">点击更改msg</button>
<hr>
<h1>{{person.name}}</h1>
<h1>{{person.age}}</h1>
<h1>{{person.a.b.c}}</h1>
<h1>{{p.a}}</h1>
<button @click="person.name = person.name + '1'">点击更改name</button>
<button @click="person.age = person.age + 1">点击更改age</button>
<button @click="person.a.b.c = person.a.b.c + '1'">点击更改name</button>
<button @click="p.a++">点击更改p.a</button>
</div>
</template>
<script>
import {ref, watch,reactive} from "vue";
export default {
name: 'WatchDemo',
setup(){
let sum = ref(0)
let msg = ref(1)
let person = ref({
name: "张三",
age: 18,
a: {
b: {
c: 6
}
}
})
let p = reactive({
a: 1,
b: 2
})
// 情况一:监视ref定义的一个响应式数据
watch(sum,(newValue, oldValue) => {
console.log('sum变了',newValue,oldValue)
},{immediate: true, deep: true})
// 情况二:监视ref所定义的多个响应式数据
// watch([sum,msg],(newValueArr,oldValueArr)=>{ //用数组存储
// console.log('sum变了',newValueArr[0],oldValueArr[0])
// console.log('msg变了',newValueArr[1],oldValueArr[1])
// })
// 监视ref中的对象
// watch(person,(newValue, oldValue)=>{
// console.log("person发生了变化",newValue, oldValue)
// },{deep: true}) // 开启深度监视可以检测到
watch(person.value,(newValue, oldValue)=>{ //或者使用.value,检测proxy
console.log("person发生了变化",newValue, oldValue)
})
//监视reactive
// watch(p,(newValue, oldValue)=>{ //或者使用.value,检测proxy
// console.log("p发生了变化",newValue, oldValue)
// }) //不需要配置deep属性,默认就是深度监视
//监视reactive的某个属性,监视多个用数组[()=>p.a,()=>p.b]
watch(()=>p.a,(newValue, oldValue)=>{ //或者使用.value,检测proxy
console.log("p发生了变化",newValue, oldValue)
})
return {
sum,
msg,
person,
p
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# 3.watchEffect函数
watch的套路是:既要指明监视的属性,也要指明监视的回调。
watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性。
watchEffect有点像computed:
- 但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值。
- 而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值。
//watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。 watchEffect(()=>{ const x1 = sum.value const x2 = person.age console.log('watchEffect配置的回调执行了') })
1
2
3
4
5
6
完整代码:
<template>
<div>
<h1>sum:{{sum}}</h1>
<button @click="sum++">点击++</button>
<h1>msg:{{msg}}</h1>
<button @click="msg = msg + '1'">点击更改msg</button>
<hr>
<h1>{{person.name}}</h1>
<h1>{{person.age}}</h1>
<h1>{{person.a.b.c}}</h1>
<h1>{{p.a}}</h1>
<button @click="person.name = person.name + '1'">点击更改name</button>
<button @click="person.age = person.age + 1">点击更改age</button>
<button @click="person.a.b.c = person.a.b.c + '1'">点击更改c</button>
<button @click="p.a++">点击更改p.a</button>
</div>
</template>
<script>
import {reactive, ref, watchEffect} from "vue";
export default {
name: 'WatchEffectDemo',
setup(){
let sum = ref(0)
let msg = ref(1)
let person = ref({
name: "张三",
age: 18,
a: {
b: {
c: 6
}
}
})
let p = reactive({
a: 1,
b: 2
})
watchEffect(() => { //函数代码块里用到谁,就会监视谁
const x = sum.value
const y = person.value.a.b.c
const z= p.a
console.log("watchEffect回调函数被调用了")
})
return {
sum,
msg,
person,
p
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 生命周期
# vue2生命周期函数示意图
# vue3生命周期函数示意图
- Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有有两个被更名:
beforeDestroy
改名为beforeUnmount
destroyed
改名为unmounted
- Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:
beforeCreate
===>setup()
created
=======>setup()
beforeMount
===>onBeforeMount
mounted
=======>onMounted
beforeUpdate
===>onBeforeUpdate
updated
=======>onUpdated
beforeUnmount
==>onBeforeUnmount
unmounted
=====>onUnmounted
完整代码:
当两者都使用,会优先使用setup函数里面的生命周期函数
<template>
<h2>当前求和为:{{ sum }}</h2>
<button @click="sum++">点我+1</button>
</template>
<script>
import {ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted} from 'vue'
export default {
name: 'LifeDemo',
setup() {
console.log('---setup---')
//数据
let sum = ref(0)
//通过组合式API的形式去使用生命周期钩子
onBeforeMount(() => {
console.log('---onBeforeMount---')
})
onMounted(() => {
console.log('---onMounted---')
})
onBeforeUpdate(() => {
console.log('---onBeforeUpdate---')
})
onUpdated(() => {
console.log('---onUpdated---')
})
onBeforeUnmount(() => {
console.log('---onBeforeUnmount---')
})
onUnmounted(() => {
console.log('---onUnmounted---')
})
//返回一个对象(常用)
return {sum}
},
//通过配置项的形式使用生命周期钩子
beforeCreate() {
console.log('---beforeCreate---')
},
created() {
console.log('---created---')
},
beforeMount() {
console.log('---beforeMount---')
},
mounted() {
console.log('---mounted---')
},
beforeUpdate() {
console.log('---beforeUpdate---')
},
updated() {
console.log('---updated---')
},
beforeUnmount() {
console.log('---beforeUnmount---')
},
unmounted() {
console.log('---unmounted---')
},
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
与 2.x 版本生命周期相对应的组合式 API
beforeCreate
-> 使用setup()
created
-> 使用setup()
beforeMount
->onBeforeMount
mounted
->onMounted
beforeUpdate
->onBeforeUpdate
updated
->onUpdated
beforeDestroy
->onBeforeUnmount
destroyed
->onUnmounted
errorCaptured
->onErrorCaptured
import { defineComponent } from 'vue';
<template>
<div></div>
</template>
<script lang="ts">
import { defineComponent, ref, onBeforeMount, onMounted, onBeforeUpdate, onBeforeUnmount, onUnmounted, onUpdated } from 'vue'
export default defineComponent({
// vue2.x中的生命周期钩子
beforeCreate () {
console.log('2.x中的beforeCreate...')
},
created () {
console.log('2.x中的created...')
},
beforeMount () {
console.log('2.x中的beforeMount...')
},
mounted () {
console.log('2.x中的mounted...')
},
beforeUpdate () {
console.log('2.x中的beforeUpdate...')
},
updated () {
console.log('2.x中的updated...')
},
// vue2.x中的beforeDestroy和destroyed这两个生命周期回调已经在vue3中改名了,所以,不能再使用了
beforeUnmount () {
console.log('2.x中的beforeUnmount...')
},
unmounted () {
console.log('2.x中的unmounted...')
},
setup () {
console.log('3.0中的setup')
// 响应式的数据
const msg = ref('abc')
// 按钮点击事件的回调
const update = () => {
msg.value += '==='
}
onBeforeMount(() => {
console.log('3.0中的onBeforeMount')
})
onMounted(() => {
console.log('3.0中的onMounted')
})
onBeforeUpdate(() => {
console.log('3.0中的onBeforeUpdate')
})
onUpdated(() => {
console.log('3.0中的onUpdated')
})
onBeforeUnmount(() => {
console.log('3.0中的onBeforeUnmount')
})
onUnmounted(() => {
console.log('3.0中的onUnmounted')
})
return {
msg,
update
}
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# 自定义hook函数
什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装。
类似于vue2.x中的mixin。
自定义hook的优势: 复用代码, 让setup中的逻辑更清楚易懂。
hooks/usePoint.ts
import { onMounted, onBeforeUnmount, ref} from 'vue'
export default function () {
const x = ref(-1)
const y = ref(-1)
// 点击事件的回调函数
const clickHandler = (event: MouseEvent) => {
x.value = event.pageX
y.value = event.pageY
}
// 页面已经加载完毕了,再进行点击的操作
// 页面加载完毕的生命周期组合API
onMounted(() => {
window.addEventListener('click', clickHandler)
})
// 页面卸载之前的生命周期组合API
onBeforeUnmount(() => {
window.removeEventListener('click', clickHandler)
})
return {
x,
y
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
HooksDemo.vue
<template>
<div>
<h2>自定义hook函数操作</h2>
<h2>x:{{ x }},y:{{ y }}</h2>
</div>
</template>
<script lang="ts">
import UsePoint from '../hooks/UsePoint'
import { defineComponent } from 'vue'
export default defineComponent({
name: 'HookDemo',
setup () {
const { x, y } = UsePoint()
return {
x,
y
}
}
})
</script>
<style lang="scss" scoped>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
- 利用TS泛型强化类型检查
- 需求2: 封装发ajax请求的hook函数
hooks/UseRequest.ts
import { ref } from 'vue'
import axios from 'axios'
/*
使用axios发送异步ajax请求
*/
export default function useUrlLoader<T> (url: string) {
const result = ref<T | null>(null)
const loading = ref(true)
const errorMsg = ref(null)
axios.get(url)
.then(response => {
loading.value = false
result.value = response.data
})
.catch(e => {
loading.value = false
errorMsg.value = e.message || '未知错误'
})
return {
loading,
result,
errorMsg
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
components/HookDemo2.vue
<template>
<div class="about">
<h2 v-if="loading">LOADING...</h2>
<h2 v-else-if="errorMsg">{{errorMsg}}</h2>
<!-- <ul v-else>
<li>id: {{result.id}}</li>
<li>name: {{result.name}}</li>
<li>distance: {{result.distance}}</li>
</ul> -->
<ul v-for="p in result" :key="p.id">
<li>id: {{p.id}}</li>
<li>title: {{p.title}}</li>
<li>price: {{p.price}}</li>
</ul>
<!-- <img v-if="result" :src="result[0].url" alt=""> -->
</div>
</template>
<script lang="ts">
import useRequest from '../hooks/UseRequest'
import { defineComponent, watch } from 'vue'
// 地址数据接口
interface AddressResult {
id: number;
name: string;
distance: string;
}
// 产品数据接口
interface ProductResult {
id: string;
title: string;
price: number;
}
export default defineComponent({
name: 'HookDemo2',
setup () {
const { loading, result, errorMsg } = useRequest<ProductResult[]>('/data/products.json')
watch(result, () => {
if (result.value) {
console.log(result.value.length) // 有提示
}
})
return {
loading,
result,
errorMsg
}
}
})
</script>
<style lang="scss" scoped>
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# toRef
作用:创建一个 ref 对象,其value值指向另一个对象中的某个属性。
语法:
const name = toRef(person,'name')
应用: 要将响应式对象中的某个属性单独提供给外部使用时。
扩展:
toRefs
与toRef
功能一致,但可以批量创建多个 ref 对象,语法:toRefs(person)
为源响应式对象上的某个属性创建一个 ref对象, 二者内部操作的是同一个数据值, 更新时二者是同步的
区别ref: 拷贝了一份新的数据值单独操作, 更新时相互不影响
应用: 当要将 某个prop 的 ref 传递给复合函数时,toRef 很有用
完整代码:
<template>
<div class="">
字母: {{ str }}
<!-- 数量: {{ number.count }}<br/> -->
<button @click="update">点击更新</button>
</div>
</template>
<script lang="ts">
import { reactive, defineComponent, toRefs } from 'vue'
export default defineComponent({
name: 'ToRef',
/*
toRefs:
将响应式对象中所有属性包装为ref对象, 并返回包含这些ref对象的普通对象
应用: 当从合成函数返回响应式对象时,toRefs 非常有用,
这样消费组件就可以在不丢失响应式的情况下对返回的对象进行分解使用
*/
setup () {
const state = reactive({
str: 'abc',
number: {
count: 0
}
})
const stateRef = toRefs(state)
function update () {
state.str += '==' // 使用扩展运算符导出去,这个不会更新
state.number.count++ // 这个会更新
}
const { str } = stateRef
// 定时器,更新数据,(如果数据变化了,界面也会随之变化,肯定是响应式的数据)
setInterval(() => {
str.value += '++++'
console.log('======')
}, 1000)
return {
// ...state, // 取出的值变为非响应式了
str,
// ...stateRef,
update
}
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<template>
<div>
<h1>{{person}}</h1>
<h1>{{name}}</h1>
<h1>{{age}}</h1>
<h1>{{job.type}}</h1>
<h1>{{job.salary}}</h1>
<button @click="name = name + '1'">更改姓名</button>
<button @click="job.salary = job.salary + '1'">更改工资</button>
</div>
</template>
<script>
import {reactive, toRef,toRefs} from "vue";
export default {
name: 'ToRefDemo',
setup() {
let person = reactive({
name: '张三',
age: 18,
job:{
type: "UI设计师",
salary: '18k'
},
})
return {
// name: toRef(person,'name'),
// age: toRef(person,'age'),
// type: toRef(person.job,'type'),
// salary: toRef(person.job,'salary'),
...toRefs(person),
person
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
toRefParent.vue
<template>
<h2>toRef的使用及特点:</h2>
<h3>state:{{ state }}</h3>
<h3>age:{{ age }}</h3>
<h3>money:{{ money }}</h3>
<hr />
<button @click="update">更新数据</button>
<hr />
<toRefChild :age="age" />
</template>
<script lang="ts">
import { defineComponent, reactive, toRef, ref } from 'vue'
import toRefChild from './toRefChild.vue'
export default defineComponent({
name: 'toRefParent',
components: {
toRefChild
},
setup () {
const state = reactive({
age: 5,
money: 100
})
// 把响应式数据state对象中的某个属性age变成了ref对象了
const age = toRef(state, 'age')
// 把响应式对象中的某个属性使用ref进行包装,变成了一个ref对象
const money = ref(state.money)
console.log(age)
console.log(money)
const update = () => {
// 更新数据的
// console.log('测试')
state.age += 2
// age.value += 3
// money.value += 10
}
return {
state,
age,
money,
update
}
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
toRefChild.vue
<template>
<h2>Child子级组件</h2>
<h3>age:{{ age }}</h3>
<h3>length:{{ length }}</h3>
</template>
<script lang="ts">
import { defineComponent, computed, Ref, toRef } from 'vue'
function useGetLength (age: Ref) {
return computed(() => {
return age.value.toString().length
})
}
export default defineComponent({
name: 'toRefChild',
props: {
age: {
type: Number,
required: true // 必须的
}
},
setup (props) {
const length = useGetLength(toRef(props, 'age'))
return {
length
}
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# ref获取元素
利用ref函数获取组件中的标签元素
功能需求: 让输入框自动获取焦点
<template>
<h2>ref的另一个作用:可以获取页面中的元素</h2>
<input type="text">---
<input type="text" ref="inputRef">
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
/*
ref获取元素: 利用ref函数获取组件中的标签元素
功能需求: 让输入框自动获取焦点
*/
export default defineComponent({
name: 'RefDemo',
setup () {
const inputRef = ref<HTMLElement | null>(null)
onMounted(() => {
inputRef.value && inputRef.value.focus()
})
return {
inputRef
}
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 三、其它 Composition API
# shallowReactive 与 shallowRef
shallowReactive:只处理对象最外层属性的响应式(浅响应式)。
shallowRef:只处理基本数据类型的响应式, 不进行对象的响应式处理。
什么时候使用?
- 如果有一个对象数据,结构比较深, 但变化时只是外层属性变化 ===> shallowReactive。
- 如果有一个对象数据,后续功能不会修改该对象中的属性,而是生新的对象来替换 ===> shallowRef。
<template>
<div>
<h1>{{person}}</h1>
<h1>{{name}}</h1>
<h1>{{age}}</h1>
<h1>{{job.type}}</h1>
<h1>{{job.salary}}</h1>
<button @click="name = name + '1'">更改姓名</button>
<button @click="job.salary = job.salary + '1'">更改工资</button>
<hr>
<h1>{{x.y}}</h1>
<button @click="x.y++">点我++</button>
</div>
</template>
<script>
import {reactive, shallowReactive, toRef, toRefs, ref, shallowRef} from "vue";
export default {
name: 'ShallowDemo',
setup() {
let person = shallowReactive({ // 只有第一层响应式
name: '张三',
age: 18,
job:{
type: "UI设计师",
salary: '18k'
},
})
//let x = shallowRef(0) 只会影响集合类型
let x = shallowRef({
y:0
})
return {
...toRefs(person),
person,
x
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# readonly 与 shallowReadonly
- readonly: 让一个响应式数据变为只读的(深只读)。
- shallowReadonly:让一个响应式数据变为只读的(浅只读)。
- 应用场景: 不希望数据被修改时。
<template>
<div>
<h1>{{name}}</h1>
<h1>{{age}}</h1>
<h1>{{job.type}}</h1>
<h1>{{job.salary}}</h1>
<button @click="name = name + '1'">更改姓名</button>
<button @click="job.salary = job.salary + '1'">更改工资</button>
<hr>
<h1>{{x}}</h1>
<button @click="x++">点我++</button>
</div>
</template>
<script>
import {reactive, toRefs, ref,readonly,shallowReadonly } from "vue";
export default {
name: 'ReadOnlyDemo',
setup() {
let x = ref(0)
let person = reactive({
name: '张三',
age: 18,
job:{
type: "UI设计师",
salary: '18k'
},
})
// person = readonly(person) // 不允许修改
person = shallowReadonly(person) // 第一层不允许修改
x = readonly(x)
return {
...toRefs(person),
x
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# toRaw 与 markRaw
- toRaw:
- 作用:将一个由
reactive
生成的响应式对象转为普通对象。 - 使用场景:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作,不会引起页面更新。
- 作用:将一个由
- markRaw:
- 作用:标记一个对象,使其永远不会再成为响应式对象。
- 应用场景:
- 有些值不应被设置为响应式的,例如复杂的第三方类库等。
- 当渲染具有不可变数据源的大列表时,跳过响应式转换可以提高性能。
<template>
<h4>当前求和为:{{sum}}</h4>
<button @click="sum++">点我++</button>
<hr>
<h2>姓名:{{name}}</h2>
<h2>年龄:{{age}}</h2>
<h2>薪资:{{job.j1.salary}}K</h2>
<h3 v-show="person.car">座驾信息:{{person.car}}</h3>
<button @click="name+='~'">修改姓名</button>
<button @click="age++">增长年龄</button>
<button @click="job.j1.salary++">涨薪</button>
<button @click="showRawPerson">输出最原始的person</button>
<button @click="addCar">给人添加一台车</button>
<button @click="person.car.name+='!'">换车名</button>
<button @click="changePrice">换价格</button>
</template>
<script>
import {ref,reactive,toRefs,toRaw,markRaw} from 'vue'
export default {
name: 'toRowDemo',
setup(){
//数据
let sum = ref(0)
let person = reactive({
name:'张三',
age:18,
job:{
j1:{
salary:20
}
}
})
function showRawPerson(){
const p = toRaw(person) // 原始集合形式输出
p.age++
console.log(p)
}
function addCar(){
let car = {name:'奔驰',price:40}
person.car = markRaw(car) // 标记一个对象,使其永远不会再成为响应式对
}
function changePrice(){
person.car.price++
console.log(person.car.price)
}
//返回一个对象(常用)
return {
sum,
person,
...toRefs(person),
showRawPerson,
addCar,
changePrice
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# customRef
作用:创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制。
实现防抖效果:
<template> <h2>CustomRef</h2> <input v-model="keyword" placeholder="搜索关键字"/> <p>{{keyword}}</p> </template> <script lang="ts"> /* customRef: 创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制 需求: 使用 customRef 实现 debounce 的示例 */ import { customRef, defineComponent } from 'vue' export default defineComponent({ name: 'CustomRef', setup () { const keyword = useDebouncedRef('', 500) console.log(keyword) return { keyword } } }) /* 实现函数防抖的自定义ref */ function useDebouncedRef<T> (value: T, delay = 200) { let timeout: number return customRef((track, trigger) => { return { get () { // 告诉Vue追踪数据 track() return value }, set (newValue: T) { clearTimeout(timeout) timeout = setTimeout(() => { value = newValue // 告诉Vue去触发界面更新 trigger() }, delay) } } }) } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54<template> <input type="text" v-model="keyword"> <h3>{{keyword}}</h3> </template> <script> import {ref,customRef} from 'vue' export default { name:'Demo', setup(){ // let keyword = ref('hello') //使用Vue准备好的内置ref //自定义一个myRef function myRef(value,delay){ let timer //通过customRef去实现自定义 return customRef((track,trigger)=>{ return{ get(){ track() //告诉Vue这个value值是需要被“追踪”的 return value }, set(newValue){ clearTimeout(timer) timer = setTimeout(()=>{ value = newValue trigger() //告诉Vue去更新界面 },delay) } } }) } let keyword = myRef('hello',500) //使用程序员自定义的ref return { keyword } } } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# provide 与 inject
作用:实现祖与后代组件间通信
套路:父组件有一个
provide
选项来提供数据,后代组件有一个inject
选项来开始使用这些数据具体写法:
祖组件中:
setup(){ ...... let car = reactive({name:'奔驰',price:'40万'}) provide('car',car) ...... }
1
2
3
4
5
6后代组件中:
setup(props,context){ ...... const car = inject('car') return {car} ...... }
1
2
3
4
5
6
<template>
<h1>父组件</h1>
<p>当前颜色: {{color}}</p>
<button @click="color='red'">红</button>
<button @click="color='yellow'">黄</button>
<button @click="color='blue'">蓝</button>
<hr>
<Son />
</template>
<script lang="ts">
import { provide, ref } from 'vue'
/*
- provide` 和 `inject` 提供依赖注入,功能类似 2.x 的 `provide/inject
- 实现跨层级组件(祖孙)间通信
*/
import Son from './Son.vue'
export default {
name: 'ProvideInject',
components: {
Son
},
setup() {
const color = ref('red')
provide('color', color)
return {
color
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<template>
<div>
<h2>子组件</h2>
<hr>
<GrandSon />
</div>
</template>
<script lang="ts">
import GrandSon from './GrandSon.vue'
export default {
components: {
GrandSon
},
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<template>
<h3 :style="{color}">孙子组件: {{color}}</h3>
</template>
<script lang="ts">
import { inject } from 'vue'
export default {
setup() {
const color = inject('color')
return {
color
}
}
}
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 响应式数据的判断
- isRef: 检查一个值是否为一个 ref 对象
- isReactive: 检查一个对象是否是由
reactive
创建的响应式代理 - isReadonly: 检查一个对象是否是由
readonly
创建的只读代理 - isProxy: 检查一个对象是否是由
reactive
或者readonly
方法创建的代理
# 手写组合API
Vue3中的响应式原理,为什么使用Proxy(代理) 与 Reflect(反射)? (opens new window)
语法:const p = new Proxy( target, handler );
参数:
target:要使用 Proxy 包装的目标对象(可以是任何类型的对象,包括原生数组,函数,甚至另一个代理)
handler:一个通常以函数作为属性的对象,各属性中的函数分别定义了在执行各种操作时代理 p 的行为。 Vue3 的响应式是通过 Proxy(代理) 配合 Reflect(反射) 进行设计
# shallowReactive 与 reactive
const reactiveHandler = {
get (target, key) {
if (key==='_is_reactive') return true
return Reflect.get(target, key)
},
set (target, key, value) {
const result = Reflect.set(target, key, value)
console.log('数据已更新, 去更新界面')
return result
},
deleteProperty (target, key) {
const result = Reflect.deleteProperty(target, key)
console.log('数据已删除, 去更新界面')
return result
},
}
/*
自定义shallowReactive
*/
function shallowReactive(obj) {
return new Proxy(obj, reactiveHandler)
}
/*
自定义reactive
*/
function reactive (target) {
if (target && typeof target==='object') {
if (target instanceof Array) { // 数组
target.forEach((item, index) => {
target[index] = reactive(item)
})
} else { // 对象
Object.keys(target).forEach(key => {
target[key] = reactive(target[key])
})
}
const proxy = new Proxy(target, reactiveHandler)
return proxy
}
return target
}
/* 测试自定义shallowReactive */
const proxy = shallowReactive({
a: {
b: 3
}
})
proxy.a = {b: 4} // 劫持到了
proxy.a.b = 5 // 没有劫持到
/* 测试自定义reactive */
const obj = {
a: 'abc',
b: [{x: 1}],
c: {x: [11]},
}
const proxy = reactive(obj)
console.log(proxy)
proxy.b[0].x += 1
proxy.c.x[0] += 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# shallowRef 与 ref
/*
自定义shallowRef
*/
function shallowRef(target) {
const result = {
_value: target, // 用来保存数据的内部属性
_is_ref: true, // 用来标识是ref对象
get value () {
return this._value
},
set value (val) {
this._value = val
console.log('set value 数据已更新, 去更新界面')
}
}
return result
}
/*
自定义ref
*/
function ref(target) {
if (target && typeof target==='object') {
target = reactive(target)
}
const result = {
_value: target, // 用来保存数据的内部属性
_is_ref: true, // 用来标识是ref对象
get value () {
return this._value
},
set value (val) {
this._value = val
console.log('set value 数据已更新, 去更新界面')
}
}
return result
}
/* 测试自定义shallowRef */
const ref3 = shallowRef({
a: 'abc',
})
ref3.value = 'xxx'
ref3.value.a = 'yyy'
/* 测试自定义ref */
const ref1 = ref(0)
const ref2 = ref({
a: 'abc',
b: [{x: 1}],
c: {x: [11]},
})
ref1.value++
ref2.value.b[0].x++
console.log(ref1, ref2)
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# shallowReadonly 与 readonly
const readonlyHandler = {
get (target, key) {
if (key==='_is_readonly') return true
return Reflect.get(target, key)
},
set () {
console.warn('只读的, 不能修改')
return true
},
deleteProperty () {
console.warn('只读的, 不能删除')
return true
},
}
/*
自定义shallowReadonly
*/
function shallowReadonly(obj) {
return new Proxy(obj, readonlyHandler)
}
/*
自定义readonly
*/
function readonly(target) {
if (target && typeof target==='object') {
if (target instanceof Array) { // 数组
target.forEach((item, index) => {
target[index] = readonly(item)
})
} else { // 对象
Object.keys(target).forEach(key => {
target[key] = readonly(target[key])
})
}
const proxy = new Proxy(target, readonlyHandler)
return proxy
}
return target
}
/* 测试自定义readonly */
/* 测试自定义shallowReadonly */
const objReadOnly = readonly({
a: {
b: 1
}
})
const objReadOnly2 = shallowReadonly({
a: {
b: 1
}
})
objReadOnly.a = 1
objReadOnly.a.b = 2
objReadOnly2.a = 1
objReadOnly2.a.b = 2
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# isRef, isReactive 与 isReadonly
/*
判断是否是ref对象
*/
function isRef(obj) {
return obj && obj._is_ref
}
/*
判断是否是reactive对象
*/
function isReactive(obj) {
return obj && obj._is_reactive
}
/*
判断是否是readonly对象
*/
function isReadonly(obj) {
return obj && obj._is_readonly
}
/*
是否是reactive或readonly产生的代理对象
*/
function isProxy (obj) {
return isReactive(obj) || isReadonly(obj)
}
/* 测试判断函数 */
console.log(isReactive(reactive({})))
console.log(isRef(ref({})))
console.log(isReadonly(readonly({})))
console.log(isProxy(reactive({})))
console.log(isProxy(readonly({})))
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 四、Composition API 的优势
# Options API 存在的问题
使用传统OptionsAPI中,新增或者修改一个需求,就需要分别在data,methods,computed里修改 。
# Composition API 的优势
我们可以更加优雅的组织我们的代码,函数。让相关功能的代码更加有序的组织在一起。
# 五、新的组件
# Fragment
- 在Vue2中: 组件必须有一个根标签
- 在Vue3中: 组件可以没有根标签, 内部会将多个标签包含在一个Fragment虚拟元素中
- 好处: 减少标签层级, 减小内存占用
# Teleport
什么是Teleport?——
Teleport
是一种能够将我们的组件html结构移动到指定位置的技术。比如
<div id = "abc"></div>
to = "#abc",将来就会穿梭到这个div里面<teleport to="移动位置"> <div v-if="isShow" class="mask"> <div class="dialog"> <h3>我是一个弹窗</h3> <button @click="isShow = false">关闭弹窗</button> </div> </div> </teleport>
1
2
3
4
5
6
7
8
<template>
<button @click="modalOpen = true">打开一个对话框</button>
<!--对话框代码-->
<Teleport to="nody">
<div v-if="modalOpen" class="modal">
<div>
这是对话框
<button @click="modalOpen = false">关闭对话框</button>
</div>
</div>
</Teleport>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
name: 'ModalButton',
setup () {
// 控制对话框显示或者隐藏的
const modalOpen = ref(false)
return {
modalOpen
}
}
})
</script>
<style>
.modal {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.modal div {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: white;
width: 300px;
height: 300px;
padding: 5px;
}
</style>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Suspense
等待异步组件时渲染一些额外内容,让应用有更好的用户体验
使用步骤:
异步引入组件
import {defineAsyncComponent} from 'vue' const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
1
2使用
Suspense
包裹组件,并配置好default
与fallback
<template> <div class="app"> <h3>我是App组件</h3> <Suspense> <template v-slot:default> <Child/> </template> <template v-slot:fallback> <h3>加载中.....</h3> </template> </Suspense> </div> </template>
1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<h2>父级组件:Suspense组件的使用</h2>
<Suspense>
<template #default>
<!--异步组件-->
<AsyncAddress />
</template>
<template v-slot:fallback>
<!--loading的内容-->
<h2>Loading.....</h2>
</template>
</Suspense>
</template>
<script lang="ts">
import { defineComponent, defineAsyncComponent } from 'vue'
// 引入组件:静态引入和动态引入
// Vue2中的动态引入组件的写法:(在Vue3中这种写法不行)
// const AsyncComponent = () => import('./AsyncComponent.vue')
// Vue3中的动态引入组件的写法
// const AsyncComponent = defineAsyncComponent(
// () => import('./AsyncComponent.vue')
// )
// 静态引入组件
import AsyncAddress from './AsyncAddress.vue'
export default defineComponent({
name: 'App',
components: {
AsyncAddress
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
<h2>AsyncComponent子级组件</h2>
<h3>{{ msg }}</h3>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
name: 'AsyncComponent',
setup () {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
msg: 'what are you no sha lei'
})
}, 2000)
})
}
})
</script>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 六、其他
# 全局API的转移
Vue 2.x 有许多全局 API 和配置。
例如:注册全局组件、注册全局指令等。
//注册全局组件 Vue.component('MyButton', { data: () => ({ count: 0 }), template: '<button @click="count++">Clicked {{ count }} times.</button>' }) //注册全局指令 Vue.directive('focus', { inserted: el => el.focus() }
1
2
3
4
5
6
7
8
9
10
11
12
Vue3.0中对这些API做出了调整:
将全局的API,即:
Vue.xxx
调整到应用实例(app
)上2.x 全局 API( Vue
)3.x 实例 API ( app
)Vue.config.xxxx app.config.xxxx Vue.config.productionTip 移除 Vue.component app.component Vue.directive app.directive Vue.mixin app.mixin Vue.use app.use Vue.prototype app.config.globalProperties
# 其他改变
data选项应始终被声明为一个函数。
过度类名的更改:
Vue2.x写法
.v-enter, .v-leave-to { opacity: 0; } .v-leave, .v-enter-to { opacity: 1; }
1
2
3
4
5
6
7
8Vue3.x写法
.v-enter-from, .v-leave-to { opacity: 0; } .v-leave-from, .v-enter-to { opacity: 1; }
1
2
3
4
5
6
7
8
9
移除keyCode作为 v-on 的修饰符,同时也不再支持
config.keyCodes
移除
v-on.native
修饰符父组件中绑定事件
<my-component v-on:close="handleComponentEvent" v-on:click="handleNativeClickEvent" />
1
2
3
4子组件中声明自定义事件
<script> export default { emits: ['close'] } </script>
1
2
3
4
5
移除过滤器(filter)
过滤器虽然这看起来很方便,但它需要一个自定义语法,打破大括号内表达式是 “只是 JavaScript” 的假设,这不仅有学习成本,而且有实现成本!建议用方法调用或计算属性去替换过滤器。
......