软件开发定制定制vue3的基本使用(超详细)

一、初识

1.vue3简介

  • 2020年9月18日,vue3发布3.0版本,软件开发定制定制代号大海贼时代来临,One Piece
  • 特点:
    • 软件开发定制定制无需构建步骤,软件开发定制定制渐进式增强静态的 HTML
    • 软件开发定制定制在任何页面中作为 Web Components 嵌入
    • 单页应用 (SPA)
    • 全栈 / 软件开发定制定制服务端渲染 (SSR)
    • Jamstack / 软件开发定制定制静态站点生成 (SSG)
    • 软件开发定制定制开发桌面端、移动端、WebGL,软件开发定制定制甚至是命令行终端中的界面

2.Vue3软件开发定制定制带来了什么

  • 软件开发定制定制打包大小减少40%
  • 软件开发定制定制初次渲染快55%,软件开发定制定制更新渲染快133%
  • 内存减少54%

3.软件开发定制定制分析目录结构

  • main.js中的引入
  • 在模板中vue3软件开发定制定制中是可以没有根标签了,软件开发定制定制这也是比较重要的改变
  • 软件开发定制定制应用实例并不只限于一个。createApp API 软件开发定制定制允许你在同一个页面中软件开发定制定制创建多个共存的 Vue 应用,软件开发定制定制而且每个应用都拥有自软件开发定制定制己的用于配置和全局资软件开发定制定制源的作用域。
//main.js//软件开发定制定制引入的不再是Vue软件开发定制定制构造函数了,软件开发定制定制引入的是一个名为createApp软件开发定制定制的工厂函数import {createApp} from 'vueimport App from './App.vue//软件开发定制定制创建应用实例对象-app(软件开发定制定制类似于之前vue2中的vm实例,但是app比vm更轻)createApp(APP).mount('#app')//卸载就是unmount,软件开发定制定制卸载就没了//createApp(APP).unmount('#app')//软件开发定制定制之前我们是这么写的,在vue3软件开发定制定制里面这一块就不支持了,会报错的,引入不到 import vue from 'vue'; new Vue({	render:(h) => h(App)}).$mount('#app')//软件开发定制定制多个应用实例const app1 = createApp({  /* ... */})app1.mount('#container-1')const app2 = createApp({  /* ... */})app2.mount('#container-2')
  • 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

安装vue3软件开发定制定制软件开发定制定制的开发者工具

  • 方式一: 打开chrome应用商店,搜索vue: 里面有个Vue.js devtools,软件开发定制定制且下面有个角标beta那个就是vue3的开发者工具
  • 方式二: 软件开发定制定制离线模式下,软件开发定制定制可以直接将包丢到扩展程序

二、 常用Composition API(组合式API)

1. setup函数

  1. 理解:Vue3.0软件开发定制定制中一个新的额配置项,软件开发定制定制值为一个函数

  2. 2.setup是所有Composition API(组合api) “软件开发定制定制表演的舞台”

  3. 软件开发定制定制组件中所用到的:数据、方法等等,软件开发定制定制均要配置在setup中

  4. setup软件开发定制定制函数的两种返回值:

    • 软件开发定制定制若返回一个对象,软件开发定制定制则对象中的属性、方法,软件开发定制定制在模板中均可以直接使用。(重点关注)
    • 软件开发定制定制若返回一个渲染函数:软件开发定制定制则可以自定义渲染内容。
  5. 注意点:

    • 软件开发定制定制尽量不要与Vue2.x配置混用
      • Vue2.x配置(data ,methos, computed…)中访问到setup中的属性,方法
      • 但在setup软件开发定制定制中不能访问到Vue2.x配置(data.methos,compued…)
      • 如果有重名,setup优先
    • setup不能是一个async函数,因为返回值不再是return的对象,而是promise,模板看不到return对象中的属性
import {h} from 'vue'//向下兼容,可以写入vue2中的data配置项module default {	name: 'App',	setup(){		//数据		let name = '张三',		let age = 18,		//方法		function sayHello(){			console.log(name)		},		//f返回一个对象(常用)		return {			name,			age,			sayHello		}				//返回一个函数(渲染函数)		//return () => {return h('h1','学习')} 		return () => h('h1','学习')	}}
  • 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

1.1关于单文件组件<script setup></script >

  • 每个 *.vue 文件最多可以包含一个 <script setup>。(不包括一般的 <script>)
  • 这个脚本块将被预处理为组件的 setup() 函数,这意味着它将为每一个组件实例都执行。<script setup> 中的顶层绑定都将自动暴露给模板。
  • <script setup> 是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。当同时使用 SFC 与组合式 API 时该语法是默认推荐。相比于普通的 <script> 语法,它具有更多优势:
    • 更少的样板内容,更简洁的代码。
    • 能够使用纯 TypeScript 声明 props 和自定义事件。这个我下面是有说明的
    • 更好的运行时性能 (其模板会被编译成同一作用域内的渲染函数,避免了渲染上下文代理对象)。
    • 更好的 IDE 类型推导性能 (减少了语言服务器从代码中抽取类型的工作)。
(1)基本语法:
/* 里面的代码会被编译成组件 setup() 函数的内容。  这意味着与普通的 `<script>` 只在组件被首次引入的时候执行一次不同,  `<script setup>` 中的代码会在每次组件实例被创建的时候执行。*/<script setup>	console.log('hello script setup')</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
顶层的绑定会被暴露给模板

当使用 <script setup> 的时候,任何在 <script setup> 声明的顶层的绑定 (包括变量,函数声明,以及 import 导入的内容) 都能在模板中直接使用:

<script setup>// 变量const msg = '王二麻子'// 函数function log() {  console.log(msg)}</script><template>  <button @click="log">{{ msg }}</button></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

import 导入的内容也会以同样的方式暴露。这意味着我们可以在模板表达式中直接使用导入的 action 函数,而不需要通过 methods 选项来暴露它:

<script setup>import { say } from './action'</script><template>  <div>{{ say ('hello') }}</div></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
(2):

响应式状态需要明确使用响应式 API 来创建。和 setup() 函数的返回值一样,ref 在模板中使用的时候会自动解包:

<script setup>import { ref } from 'vue'const count = ref(0)</script><template>  <button @click="count++">{{ count }}</button></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
(3)使用组件:
  • <script setup> 范围里的值也能被直接作为自定义组件的标签名使用:
/***这里 MyComponent 应当被理解为像是在引用一个变量。*如果你使用过 JSX,此处的心智模型是类似的。*其 kebab-case 格式的 <my-component> 同样能在模板中使用——不过,*强烈建议使用 PascalCase 格式以保持一致性。同时这也有助于区分原生的自定义元素。*/<script setup>import MyComponent from './MyComponent.vue'</script><template>  <MyComponent /></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
动态组件
/***由于组件是通过变量引用而不是基于字符串组件名注册的,*在 <script setup> 中要使用动态组件的时候,应该使用*动态的 :is 来绑定:*/<script setup>import Foo from './Foo.vue'import Bar from './Bar.vue'</script><template>  <component :is="Foo" />  <component :is="someCondition ? Foo : Bar" /></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
递归组件
  • 一个单文件组件可以通过它的文件名被其自己所引用。例如:名为 FooBar.vue 的组件可以在其模板中用 <FooBar/> 引用它自己。
  • 注意这种方式相比于导入的组件优先级更低。如果有具名的导入和组件自身推导的名字冲突了,可以为导入的组件添加别名:
import { FooBar as FooBarChild } from './components'
  • 1
命名空间组件
  • 可以使用带 . 的组件标签,例如 <Foo.Bar> 来引用嵌套在对象属性中的组件。这在需要从单个文件中导入多个组件的时候非常有用:
<script setup>import * as Form from './form-components'</script><template>  <Form.Input>    <Form.Label>label</Form.Label>  </Form.Input></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
(4)使用自定义指令:
  • 全局注册的自定义指令将正常工作。本地的自定义指令在 <script setup> 中不需要显式注册,但他们必须遵循 vNameOfDirective 这样的命名规范:
<script setup>const vMyDirective = {  beforeMount: (el) => {    // 在元素上做些操作  }}</script><template>  <h1 v-my-directive>This is a Heading</h1></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 如果指令是从别处导入的,可以通过重命名来使其符合命名规范:
<script setup>import { myDirective as vMyDirective } from './MyDirective.js'</script>
  • 1
  • 2
  • 3
(5)defineProps() 和 defineEmits():
  • 为了在声明 props 和 emits 选项时获得完整的类型推导支持,我们可以使用 defineProps 和 defineEmits API,它们将自动地在 <script setup> 中可用:
<script setup>const props = defineProps({  foo: String})const emit = defineEmits(['change', 'delete'])// setup 代码</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • defineProps 和 defineEmits 都是只能在 <script setup> 中使用的编译器宏。他们不需要导入,且会随着 <script setup> 的处理过程一同被编译掉。
  • defineProps 接收与 props 选项相同的值,defineEmits 接收与 emits 选项相同的值。
  • defineProps 和 defineEmits 在选项传入后,会提供恰当的类型推导。
  • 传入到 defineProps 和 defineEmits 的选项会从 setup 中提升到模块的作用域。因此,传入的选项不能引用在 setup 作用域中声明的局部变量。这样做会引起编译错误。但是,它可以引用导入的绑定,因为它们也在模块作用域内。
(5)defineExpose:
  • 使用 <script setup> 的组件是默认关闭的——即通过模板引用或者 $parent 链获取到的组件的公开实例,不会暴露任何在 <script setup> 中声明的绑定。
//可以通过 defineExpose 编译器宏来显式指定在 <script setup> 组件中要暴露出去的属性:<script setup>import { ref } from 'vue'const a = 1const b = ref(2)defineExpose({  a,  b})</script>//当父组件通过模板引用的方式获取到当前组件的实例,//获取到的实例会像这样 { a: number, b: number } (ref 会和在普通实例中一样被自动解包)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
(6)useSlots() 和 useAttrs():
  • <script setup> 使用 slots 和 attrs 的情况应该是相对来说较为罕见的,因为可以在模板中直接通过 $slots 和 $attrs 来访问它们。在你的确需要使用它们的罕见场景中,可以分别用 useSlots 和 useAttrs 两个辅助函数:
<script setup>import { useSlots, useAttrs } from 'vue'const slots = useSlots()const attrs = useAttrs()</script>//useSlots 和 useAttrs 是真实的运行时函数,它的返回与 setupContext.slots 和 setupContext.attrs 等价。//它们同样也能在普通的组合式 API 中使用。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
(7)与普通的 <script> 一起使用:

<script setup> 可以和普通的 <script> 一起使用。普通的 <script> 在有这些需要的情况下或许会被使用到:

  • 声明无法在
<script>// 普通 <script>, 在模块作用域下执行 (仅一次)runSideEffectOnce()// 声明额外的选项export default {  inheritAttrs: false,  customOptions: {}}</script><script setup>// 在 setup() 作用域中执行 (对每个实例皆如此)</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
(8)顶层 await:
  • <script setup> 中可以使用顶层 await。结果代码会被编译成 async setup():
<script setup>const post = await fetch(`/api/post/1`).then((r) => r.json())</script>// 另外,await 的表达式会自动编译成在 await 之后保留当前组件实例上下文的格式。
  • 1
  • 2
  • 3
  • 4

2.ref 函数

  • 作用:定义一个响应式的数据
  • 语法: const xxx = ref(initValue)
    • 创建一个包含响应式数据引用对象(reference对象)
    • JS中操作数据:xxx.value
    • 模板中读取数据:不需要.value,直接:
      {{xxx}}
  • 备注:
    • 接收的数据可以是:基本类型、也可以是对象类型
    • 基本类型的数据:响应式依然靠的是Object.defineProperty()的get和set完成的
    • 对象类型的数据: 内部”求助“了Vue3.0中的一个新的函数——reactive函数

3.reactive 函数

  • 作用:定义一个对象类型的响应式数据(基本类型别用他,用ref函数)
  • 语法:const 代理对象 = reactive(被代理对象)接收一个对象(或数组),返回一个代理对象(proxy对象)
  • reactive定义的响应式数据是”深层次的“
  • 内部基于ES6的Proxy实现,通过代理对象操作源对象内部数据进行操作

4.Vue3.0中响应式原理

  • 先来看一看vue2的响应式原理
    • 对象类型: 通过Object.defineProperty()对属性的读取、修改进行拦截(数据劫持)
    • 数组类型:通过重写更新数组的一系列方法来实现拦截。(对数组的变更方法进行了包裹)
Object.defineProperty( data, 'count', {	get(){},	set(){}})//模拟实现一下let person = {	name: '张三',	age: 15,}let p = {}Object.defineProperty( p, 'name', {	configurable: true, //配置这个属性表示可删除的,否则delete p.name 是删除不了的 false	get(){		//有人读取name属性时调用		return person.name	},	set(value){		//有人修改时调用		person.name = value	}})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 存在问题:
    1. 新增属性。删除属性。界面不会更新
    2. 直接通过下表修改数组,界面不会自动更新
  • vue3的响应式
    • 实现原理:
      • 通过Proxy(代理):拦截对象中任意属性的变化,包括:属性值的读写、属性的添加、属性的删除等等。
      • 通过Reflect(反射):对被代理对象的属性进行操作
      • MDN文档中描述的Proxy与Reflect:可以参考对应的文档
//模拟vue3中实现响应式let person = {	name: '张三',	age: 15,}//我们管p叫做代理数据,管person叫源数据const p = new Proxy(person,{	//target代表的是person这个源对象,propName代表读取或者写入的属性名	get(target,propName){		console.log('有人读取了p上面的propName属性')		return target[propName]	},	//不仅仅是修改调用,增加的时候也会调用	set(target,propName,value){		console.log(`有人修改了p身上的${propName}属性,我要去更新界面了`)		target[propName] = value	},	deleteProperty(target,propName){		console.log(`有人删除了p身上的${propName}属性,我要去更新界面了`)		return delete target[propName]	}})//映射到person上了,捕捉到修改,那就是响应式啊
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
//vue3底层源码不是我们上面写的那么low,实现原理一样,但是用了一个新的方式window.Reflect![Reflect的写法](https://img-blog.csdnimg.cn/565f96b1be74435cacbc42e06706791d.png)let obj = {	a: 1,	b:2,}//传统的只能通过try catch去捕获异常,如果使用这种那么底层源码将会有一堆try catchtry{	Object.defineProperty( obj, 'c', {		get(){ return 3 },	})	Object.defineProperty( obj, 'c', {		get(){ return 4 },	})} catch(error) {	console.log(error)}//新的方式: 通过Reflect反射对象去操作,相对来说要舒服一点,不会要那么多的try catchconst x1 = Reflect.defineProperty( obj, 'c', {		get(){ return 3 },})const x2 = Reflect.defineProperty( obj, 'c', {		get(){ return 3 },})//x1,和x2是有返回布尔值的if(x2){	console.log('某某操作成功了')}else {	console.log('某某操作失败了')}
  • 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
  • 所以vue3最终的响应式原理如下:
let person = {	name: '张三',	age: 15,}//我们管p叫做代理数据,管person叫源数据const p = new Proxy(person,{	//target代表的是person这个源对象,propName代表读取或者写入的属性名	get(target,propName){		console.log('有人读取了p上面的propName属性')		return Reflect.get(target, propName)	},	//不仅仅是修改调用,增加的时候也会调用	set(target,propName,value){		console.log(`有人修改了p身上的${propName}属性,我要去更新界面了`)		Reflect.set(target, propName, value)	},	deleteProperty(target,propName){		console.log(`有人删除了p身上的${propName}属性,我要去更新界面了`)		return Reflect.deleteProperty(target,propName) 	}})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

5.reactive对比ref

  • 从定义数据角度对比:

    • ref用来定义: 基本数据类型
    • reactive用来定义: 对象(或数组)类型数据
    • 备注: ref也可以用来定义对象(或数组)类型数据,它内部会自动通过reactive转为代理对象
  • 从原理角度对比:

    • ref通过Object.defineProperty()的get和set来实现响应式(数据劫持)
    • reactive通过Proxy来实现响应式(数据劫持),并通过Reflect操作源对象内部的数据
  • 从使用角度对比:

    • ref定义数据:操作数据需要 .value ,读取数据时模板中直接读取不需要 .value
    • reactive 定义的数据: 操作数据和读取数据均不需要 .value

5.setup的两个注意点

  • setup执行的时机
    • 在beforeCreate之前执行一次,this是undefined
    • setup的参数
      • props:值为对象,包含: 组件外部传递过来,且组件内部声明接收了属性
      • context:上下文对象
        • attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性,相当于 this.$attrs
        • slots:收到插槽的内容,相当于$slots
        • emit: 分发自定义事件的函数,相当于this.$emit
//父组件<script setup>// This starter template is using Vue 3 <script setup> SFCs// Check out https://vuejs.org/api/sfc-script-setup.html#script-setupimport HelloWorld from './components/test3.vue';const hello = (val) =>{  console.log('传递的参数是:'+ val);}</script><template>  <img alt="Vue logo" src="./assets/logo.png" />  <HelloWorld msg="传递吧" @hello="hello">    <template v-slot:cacao>      <span>是插槽吗</span>    </template>    <template v-slot:qwe>      <span>meiyou</span>    </template>  </HelloWorld></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
//子组件export default {    name: 'test3',    props: ['msg'],    emits:['hello'],    //这里setup接收两个参数,一个是props,一个是上下文context    setup(props,context){        /**         * props就是父组件传来的值,但是他是Porxy类型的对象         * >Proxy:{msg:'传递吧'}         * 可以当作我们自定义的reactive定义的数据         */        /**         * context是一个对象 包含以下内容:         * 1.emit触发自定义事件的          * 2.attrs 相当于vue2里面的 $attrs 包含:组件外部传递过来,但没有在props配置中声明的属性         * 3.slots 相当于vue2里面的 $slots         * 3.expose 是一个回调函数         */        console.log(context.slots);        let person = reactive({            name: '张三',            age: 17,        })                function changeInfo(){            context.emit('hello', 666)        }        //返回对象        return {            person,            changeInfo        }        //返回渲染函数(了解) 这个h是个函数        //return () => h('name','age')    }}</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

6.计算属性与监视

(1)computed函数
  • 与vue2.x中的写法一致
  • 需要引入computed
<template>  <h1>一个人的信息</h1>  <div>      姓: <input type="text" v-model="person.firstName">      名:<input type="text" v-model="person.lastName">      <div>          <span>简名:{{person.smallName}}</span> <br>          <span>全名:{{person.fullName}}</span>      </div>  </div></template><script>import { computed,reactive } from 'vue'    export default {        name: 'test4',        props: ['msg'],        emits:['hello'],        setup(){            let person = reactive({                firstName: '张',                lastName: '三'            })            //简写形式            person.smallName = computed(()=>{                return person.firstName + '-' + person.lastName            })            //完全形态            person.fullName = computed({                get(){                    console.log('调用get');                    return person.firstName + '*' + person.lastName                },                set(value){                    console.log('调用set');                    const nameArr = value.split('*')                    person.firstName = nameArr[0]                    person.firstName = nameArr[1]                },            })            return {                person,            }        },            } </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
(2)watch函数
  • 和computed一样,需要引入api
  • 有两个小坑:

1.监视reactive定义的响应式数据的时候:oldValue无法获取到正确的值,强制开启了深度监视(deep配置无效)
2.监视reactive定义的响应式数据中某个属性的时候:deep配置有效
具体请看下面代码以及注释

<template>  <h1>当前求和为: {{sum}}</h1>  <button @click="sum++">点我+1</button>  <hr>  <h1>当前信息为: {{msg}}</h1>  <button @click="msg+='!' ">修改信息</button>  <hr>  <h2>姓名: {{person.name}}</h2>  <h2>年龄: {{person.age}}</h2>  <button @click="person.name += '~' ">修改姓名</button> <button @click="person.age++">增长年龄</button></template><script>    //使用setup的注意事项    import { watch,ref,reactive } from 'vue'    export default {        name: 'test5',        props: ['msg'],        emits:['hello'],        setup(){            let sum  = ref(0)            let msg = ref('你好啊')            let person = reactive({                name: '张三',                age: 18,                job:{                    salary: '15k'                },            })            //由于这里的this是指的是undefined,所以使用箭头函数            //情况一:监视ref所定义的一个响应式数据            // watch(sum, (newValue,oldValue)=>{            //     console.log('新的值',newValue);            //     console.log('旧的值',oldValue);            // })            //情况二:监视ref所定义的多个响应式数据            watch([sum,msg], (newValue,oldValue)=>{                console.log('新的值',newValue); //['sum的newValue', 'msg的newValue']                console.log('旧的值',oldValue); //['sum的oldValue', 'msg的oldValue']            },{immediate: true,deep:true}) //这里vue3的deep是有点小问题的,可以不用deep,(隐式强制deep)            //情况三:监视reactive定义的所有响应式数据,            //1.此处无法获取正确的oldValue(newValue与oldValue是一致值),且目前无法解决            //2.强制开启了深度监视(deep配置无效)            /**            * 受到码友热心评论解释: 此处附上码友的解释供大家参考:            * 1. 当你监听一个响应式对象的时候,这里的newVal和oldVal是一样的,因为他们是同一个对象【引用地址一样】,            *    即使里面的属性值会发生变化,但主体对象引用地址不变。这不是一个bug。要想不一样除非这里把对象都换了            *             * 2. 当你监听一个响应式对象的时候,vue3会隐式的创建一个深层监听,即对象里只要有变化就会被调用。            *    这也解释了你说的deep配置无效,这里是强制的。            */            watch(person, (newValue,oldValue)=>{                console.log('新的值',newValue);                 console.log('旧的值',oldValue);            })            //情况四:监视reactive对象中某一个属性的值,            //注意: 这里监视某一个属性的时候可以监听到oldValue            watch(()=>person.name, (newValue,oldValue)=>{                console.log('新的值',newValue);                  console.log('旧的值',oldValue);            })            //情况五:监视reactive对象中某一些属性的值            watch([()=>person.name,()=>person.age], (newValue,oldValue)=>{                console.log('新的值',newValue);                  console.log('旧的值',oldValue);            })            //特殊情况: 监视reactive响应式数据中深层次的对象,此时deep的配置奏效了            watch(()=>person.job, (newValue,oldValue)=>{                console.log('新的值',newValue);                  console.log('旧的值',oldValue);            },{deep:true}) //此时deep有用            return {                sum,                msg,                person,            }        },            }</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
  • 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
(3)watchEffect函数
  • watch的套路是:既要指明监视的属性,也要指明监视的回调
  • watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性
  • watchEffect有点像computed:
    • 但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值
    • 而watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值
<script>    //使用setup的注意事项    import { ref,reactive,watchEffect } from 'vue'    export default {        name: 'test5',        props: ['msg'],        emits:['hello'],        setup(){            let sum  = ref(0)            let msg = ref('你好啊')            let person = reactive({                name: '张三',                age: 18,                job:{                    salary: '15k'                },            })                        //用处: 如果是比较复杂的业务,发票报销等,那就不许需要去监听其他依赖,只要发生变化,立马重新回调            //注重逻辑过程,你发生改变了我就重新执行回调,不用就不执行,只执行一次            watchEffect(()=>{                //这里面你用到了谁就监视谁,里面就发生回调                const x1 = sum.value                console.log('我调用了');            })            return {                sum,                msg,                person,            }        },            }</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

7.生命周期函数

<template>  <h1>生命周期</h1>  <p>当前求和为: {{sum}}</p>  <button @click="sum++">加一</button></template><script>    //使用setup的注意事项    import { ref,reactive,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted } from 'vue'    export default {        name: 'test7',        setup(){           let sum = ref(0)           //通过组合式API的形式去使用生命周期钩子            /**             * beforeCreate 和  created 这两个生命周期钩子就相当于 setup 所以,不需要这两个             *              * beforeMount   ===>  onBeforeMount             * mounted       ===>  onMounted             * beforeUpdate  ===>  onBeforeUpdate             * updated       ===>  onUpdated             * beforeUnmount ===>  onBeforeUnmount             * unmounted     ===>  onUnmounted             */            console.log('---setup---');            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            }        },        //这种是外层的写法,如果想要使用组合式api的话需要放在setup中        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>
  • 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
  • 74
  • 75
  • 76
  • 77
  • 78

8.自定义hook函数

  • 什么是hook函数: 本质是一个函数,把setup函数中使用的Composition API进行了封装
  • 类似于vue2.x中的 mixin
  • 自定义hook的优势: 复用代码,让setup中的逻辑更清楚易懂
  • 使用hook实现鼠标打点”:
    创建文件夹和usePoint.js文件
//usePoint.jsimport {reactive,onMounted,onBeforeUnmount } from 'vue'function savePoint(){    //实现鼠标打点的数据    let point = reactive({        x: null,        y: null    })    //实现鼠标点的方法    const savePoint = (e)=>{         point.x = e.pageX         point.y = e.pageY    }     //实现鼠标打点的生命周期钩子    onMounted(()=>{        window.addEventListener('click',savePoint)    })    onBeforeUnmount(()=>{        window.removeEventListener('click',savePoint)    })    return point}export default savePoint
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
//组件test.vue<template>  <p>当前求和为: {{sum}} </p>  <button @click="sum++">加一</button>  <hr>  <h2>当前点击时候的坐标: x: {{point.x}}  y:{{point.y}}</h2></template><script>import { ref } from 'vue'import usePoint from '../hooks/usePoint'export default {    name: 'test8',    setup(props,context){        let sum = ref(0)        let point = usePoint()        return {            sum,            point        }    }}</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

9.toRef

  • 作用: 创建一个ref对象,其value值指向另一个对象中的某个属性值
  • 语法: const name = toRef(person, ‘name’)
  • 应用:要将响应式对象中的某个属性单独提供给外部使用
  • 扩展: toRefs与toRef功能一致,但是可以批量创建多个ref对象,语法: toRefs(person)
<template>  <h2>姓名: {{name2}}</h2>  <h2>年龄: {{person.age}}</h2>  <button @click="person.name += '~' ">修改姓名</button>   <button @click="person.age++">增长年龄</button></template><script>    //使用setup的注意事项    import { reactive, toRef, toRefs } from 'vue'    export default {        name: 'test9',        setup(){            let person = reactive({                name: '张三',                age: 18,                job:{                    salary: '15k'                },            })            //toRef            const name2 = toRef(person,'name') //第一个参数是对象,第二个参数是键名            console.log('toRef转变的是',name2); //ref定义的对象            //toRefs,批量处理对象的所有属性            //const x  = toRefs(person)            //console.log('toRefs转变的是',x); //是一个对象            return {                person,                name2,                ...toRefs(person)            }        },            }</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

三、TypeScript 与组合式 API

1.为组件的 props 标注类型

//场景一: 使用<script setup><script setup lang="ts">const props = defineProps({  foo: { type: String, required: true },  bar: Number})props.foo // stringprops.bar // number | undefined</script>//也可以将 props 的类型移入一个单独的接口中<script setup lang="ts">interface Props {  foo: string  bar?: number}const props = defineProps<Props>()</script>//场景二: 不使用<script setup>import { defineComponent } from 'vue'export default defineComponent({  props: {    message: String  },  setup(props) {    props.message // <-- 类型:string  }})
  • 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
  • 注意点:为了生成正确的运行时代码,传给 defineProps() 的泛型参数必须是以下之一:
//1.一个类型字面量:defineProps<{ /*... */ }>()//2.对同一个文件中的一个接口或对象类型字面量的引用interface Props {/* ... */}defineProps<Props>()//3.接口或对象字面类型可以包含从其他文件导入的类型引用,但是,传递给 defineProps 的泛型参数本身不能是一个导入的类型:import { Props } from './other-file'// 不支持!defineProps<Props>()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • Props 解构默认值
//当使用基于类型的声明时,失去了对 props 定义默认值的能力。通过目前实验性的响应性语法糖来解决:<script setup lang="ts">interface Props {  foo: string  bar?: number}// 对 defineProps() 的响应性解构// 默认值会被编译为等价的运行时选项const { foo, bar = 100 } = defineProps<Props>()</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

2.为组件的 emits 标注类型

//场景一: 使用<script setup><script setup lang="ts">const emit = defineEmits(['change', 'update'])// 基于类型const emit = defineEmits<{  (e: 'change', id: number): void  (e: 'update', value: string): void}>()</script>//场景二: 不使用<script setup>import { defineComponent } from 'vue'export default defineComponent({  emits: ['change'],  setup(props, { emit }) {    emit('change') // <-- 类型检查 / 自动补全  }})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

3.为 ref() 标注类型

import { ref } from 'vue'import type { Ref } from 'vue'//1.ref 会根据初始化时的值推导其类型:// 推导出的类型:Ref<number>const year = ref(2020)// => TS Error: Type 'string' is not assignable to type 'number'.year.value = '2020'//2.指定一个更复杂的类型,可以通过使用 Ref 这个类型:const year: Ref<string | number> = ref('2020')year.value = 2020 // 成功!//3.在调用 ref() 时传入一个泛型参数,来覆盖默认的推导行为:// 得到的类型:Ref<string | number>const year = ref<string | number>('2020')year.value = 2020 // 成功!//4.如果你指定了一个泛型参数但没有给出初始值,那么最后得到的就将是一个包含 undefined 的联合类型:// 推导得到的类型:Ref<number | undefined>const n = ref<number>()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

4.为reactive() 标注类型

import { reactive } from 'vue'//1.reactive() 也会隐式地从它的参数中推导类型:// 推导得到的类型:{ title: string }const book = reactive({ title: 'Vue 3 指引' })//2.要显式地标注一个 reactive 变量的类型,我们可以使用接口:interface Book {  title: string  year?: number}const book: Book = reactive({ title: 'Vue 3 指引' })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

5.为 computed() 标注类型

import { ref, computed } from 'vue'//1.computed() 会自动从其计算函数的返回值上推导出类型:const count = ref(0)// 推导得到的类型:ComputedRef<number>const double = computed(() => count.value * 2)// => TS Error: Property 'split' does not exist on type 'number'const result = double.value.split('')//2.通过泛型参数显式指定类型:const double = computed<number>(() => {  // 若返回值不是 number 类型则会报错})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

6.为事件处理函数标注类型

//在处理原生 DOM 事件时,应该为我们传递给事件处理函数的参数正确地标注类型<script setup lang="ts">function handleChange(event) {  // 没有类型标注时 `event` 隐式地标注为 `any` 类型,  // 这也会在 tsconfig.json 中配置了 "strict": true 或 "noImplicitAny": true 时报出一个 TS 错误。  console.log(event.target.value)}</script><template>  <input type="text" @change="handleChange" /></template>//因此,建议显式地为事件处理函数的参数标注类型,需要显式地强制转换 event 上的属性:function handleChange(event: Event) {  console.log((event.target as HTMLInputElement).value)}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

7.为 provide / inject 标注类型

/*provide 和 inject 通常会在不同的组件中运行。要正确地为注入的值标记类型,Vue 提供了一个 InjectionKey 接口,它是一个继承自 Symbol 的泛型类型,可以用来在提供者和消费者之间同步注入值的类型:*/import { provide, inject } from 'vue'import type { InjectionKey } from 'vue'const key = Symbol() as InjectionKey<string>provide(key, 'foo') // 若提供的是非字符串值会导致错误const foo = inject(key) // foo 的类型:string | undefined//建议将注入 key 的类型放在一个单独的文件中,这样它就可以被多个组件导入。//当使用字符串注入 key 时,注入值的类型是 unknown,需要通过泛型参数显式声明:const foo = inject<string>('foo') // 类型:string | undefined//注意注入的值仍然可以是 undefined,因为无法保证提供者一定会在运行时 provide 这个值。//当提供了一个默认值后,这个 undefined 类型就可以被移除:const foo = inject<string>('foo', 'bar') // 类型:string//如果你确定该值将始终被提供,则还可以强制转换该值:const foo = inject('foo') as string
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

8.为模板引用标注类型

//模板引用需要通过一个显式指定的泛型参数和一个初始值 null 来创建:<script setup lang="ts">import { ref, onMounted } from 'vue'const el = ref<HTMLInputElement | null>(null)onMounted(() => {  el.value?.focus()})</script>/**	注意为了严格的类型安全,有必要在访问 el.value 时使用可选链或类型守卫。这是因为直到组件被挂载前,	这个 ref 的值都是初始的 null,并且在由于 v-if 的行为将引用的元素卸载时也可以被设置为 null。*/<template>  <input ref="el" /></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

9.为组件模板引用标注类型

//有时,你可能需要为一个子组件添加一个模板引用,以便调用它公开的方法。举例来说,我们有一个 MyModal 子组件,它有一个打开模态框的方法<!-- MyModal.vue --><script setup lang="ts">import { ref } from 'vue'const isContentShown = ref(false)const open = () => (isContentShown.value = true)defineExpose({  open})</script>//为了获取 MyModal 的类型,我们首先需要通过 typeof 得到其类型,再使用 TypeScript 内置的 InstanceType 工具类型来获取其实例类型:<!-- App.vue --><script setup lang="ts">import MyModal from './MyModal.vue'const modal = ref<InstanceType<typeof MyModal> | null>(null)const openModal = () => {  modal.value?.open()}</script>//注意,如果你想在 TypeScript 文件而不是在 Vue SFC 中使用这种技巧,需要开启 Volar 的Takeover 模式。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

四、Vuex与组合式API

  • 组合式API 可以通过调用 useStore 函数,来在 setup 钩子函数中访问 store。这与在组件中使用选项式 API 访问 this.$store 是等效的。
import { useStore } from 'vuex'export default {  setup () {    const store = useStore()  }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

1.访问 state 和 getter

  • 为了访问 state 和 getter,需要创建 computed 引用以保留响应性,这与在选项式 API 中创建计算属性等效。
import { computed } from 'vue'import { useStore } from 'vuex'export default {  setup () {    const store = useStore()    return {      // 在 computed 函数中访问 state      count: computed(() => store.state.count),      // 在 computed 函数中访问 getter      double: computed(() => store.getters.double)    }  }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

2.访问 Mutation 和 Action

  • 要使用 mutation 和 action 时,只需要在 setup 钩子函数中调用 commit 和 dispatch 函数。
import { useStore } from 'vuex'export default {  setup () {    const store = useStore()    return {      // 使用 mutation      increment: () => store.commit('increment'),      // 使用 action      asyncIncrement: () => store.dispatch('asyncIncrement')    }  }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

五、 其他的Composition API

1.shallowReactive与shallowRef

  • shallowReactive:只处理对象最外层属性的响应式(浅响应式)只考虑第一层数据的响应式。
  • shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理,传递基本数据类型的话跟ref没有任何区别,ref是可以进行对象的响应式处理的

我们正常的ref创建的数据,里面的.value是一个proxy,而shallowRef创建的数据 .value里面是一个object数据类型,所以不会响应式数据

  • 什么时候使用?:
    • 如果有一个对象数据,结构比较深,但变化时只是外层属性变化 ===> shallowReactive
    • 如果有一个对象数据,后续功能不会修改对象中的属性,而是生新的对象来替换 ===> shallowRef

2.readonly与shallowReadonly

  • readonly:让一个响应式的数据变成只读的(深只读)
  • shallowReadonly: 让一个响应式数据变成只读的(浅只读)
  • 应用场景:不希望数据被修改的时候
<script>    import { reactive,readonly,shallowReadonly } from 'vue'    export default {        name: 'test9',        setup(){            let person = reactive({				name: '张三',				job:{					salary: '20k',				}			})			person = readonly(person) //这个时候修改人的信息就不会改变了,所有的都不能改			/**			* 页面不进行响应式的改变,一般存在两种情况:			* 1.setup里面定义的数据改变了,但是vue没有检测到,这个时候是不会改变的			* 2.setup里面定义的数据压根儿就不让你改,这个时候也没法响应式			*/			person = shallowReadonly(person) //只有最外层不能修改是只读的,但是job还是可以改的            return {                person            }        },    }</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

3.toRaw与markRaw

  • toRaw
    • 作用:将一个由reactive生成的响应式对象转换为普通对象
    • 使用场景:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作,不会引起页面更新
  • markRaw:
    • 作用:标记一个对象,使其永远不会再成为响应式对象
    • 使用场景:
      • 1.有些值不应被设置成响应式的,例如复杂的第三方类库等
      • 2.当渲染具有不可变数据的大列表时候,跳过响应式转换可以提高性能
import {reactive,toRaw,markRaw} from 'vue'setup(){	let person = reactive({		name: '张三',	})	function showRawPerson(){		const p = toRaw(person)		p.age++		console.log(p)	}	function addCar(){		let car = {name: '奔驰'}		person.car = markRaw(car) //一旦这么做时候,他就永远不能当成响应式数据去做了	}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

4.customRef

  • 创建一个自定义的ref,并对其依赖项跟踪和更新触发进行显示控制
  • 实现防抖效果:
<template>    <input type="text" v-model="keyword">    <h3>{{keyword}}</h3></template><script>    import { customRef, ref } from 'vue'    export default {        name: 'test10',        setup(){            let timer;            //自定义一个ref——名为: myRef            function myRef(value){                return customRef((track,trigger)=>{                    return {                        get(){                            console.log(`有人读取我的值了,要把${value}给他`);  //两次输出: v-model读取  h3里面的插值语法调了一次                            track()  //追踪一下改变的数据(提前跟get商量一下,让他认为是有用的)                            return value                        },                        set(newValue){                            console.log(`有人把myRef这个容器中数据改了:${newValue}`);                            clearTimeout(timer)                            timer = setTimeout(()=>{                                value = newValue                                trigger() //通知vue去重新解析模板,重新再一次调用get()                            },500)                        }                    }                })            }            // let keyword = ref('hello')  //使用内置提供的ref            let keyword = myRef('hello')  //使用自定义的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
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44

5.provide与inject

  • 作用:实现祖孙组件间的通信
  • 套路:父组件有一个provide选项提供数据,子组件有一个inject选项来开始使用这些数据
  • 具体写法:
//父组件<script setup>import { ref,reactive,toRefs,provide } from 'vue';import ChildVue from './components/Child.vue';let car = reactive({  name: '奔驰',  price: '40w'})provide('car',car) //给自己的后代组件传递数据const {name, price} = toRefs(car)</script><template>  <div class="app">    <h3>我是父组件, {{name}}--{{price}}</h3>    <ChildVue></ChildVue>  </div></template><style>.app{  background-color: gray;  padding: 10px;  box-sizing: border-box;}</style>
  • 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
//子组件<script setup>import { ref } from '@vue/reactivity';import SonVue from './Son.vue';</script><template>  <div class="app2">    <h3>我是子组件</h3>    <SonVue></SonVue>  </div></template><style>.app2{  background-color: rgb(82, 150, 214);  padding: 10px;  box-sizing: border-box;}</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
//孙组件<script setup>import { ref,inject } from 'vue';let car = inject('car') //拿到父组件的数据const {name, price} = car</script><template>  <div class="app3">    <h3>我是孙组件</h3>    <p>{{name}}-{{price}}</p>  </div></template><style>.app3{  background-color: rgb(231, 184, 56);  padding: 10px;  box-sizing: border-box;}</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

6.响应式数据的判断

  • isRef:检查一个值是否为ref对象
  • isReactivce:检查一个对象是否是由reactive创建的响应式代理
  • isReadonly:检查一个对象是否由readonly创建的只读代理
  • isProxy:检查一个对象是否由reactive或者readonly方法创建的代理

六、Composition API的优势

1.传统options API存在的问题

  • 使用传统的Options API中,新增或者修改一个需求,就需要分别在data,methods,computed里面修改

2.Composition API的优势

  • 我们可以更加优雅的组织我们的代码,函数,让相关功能的代码更加有序的组织在一起

七、新的组件

1.Transition

  • 会在一个元素或组件进入和离开 DOM 时应用动画
  • 它是一个内置组件,这意味着它在任意别的组件中都可以被使用,无需注册。它可以将进入和离开动画应用到通过默认插槽传递给它的元素或组件上。进入或离开可以由以下的条件之一触发:
    • 由 v-if 所触发的切换
    • 由 v-show 所触发的切换
    • 由特殊元素 切换的动态组件
<button @click="show = !show">切换</button><Transition>  <p v-if="show">HelloWord</p></Transition>//当一个 <Transition> 组件中的元素被插入或移除时,会发生下面这些事情/**1.Vue 会自动检测目标元素是否应用了 CSS 过渡或动画。如果是,则一些 CSS 过渡 class 会在适当的时机被添加和移除2.如果有作为监听器的 JavaScript 钩子,这些钩子函数会在适当时机被调用3.如果没有探测到 CSS 过渡或动画、也没有提供 JavaScript 钩子,那么 DOM 的插入、删除操作将在浏览器的下一个动画帧后执行*///针对CSS 的过渡效果/**1.v-enter-from:进入动画的起始状态。在元素插入之前添加,在元素插入完成后的下一帧移除。2.v-enter-active:进入动画的生效状态。应用于整个进入动画阶段。在元素被插入之前添加,在过渡或动画完成之后移除。这个 class 可以被用来定义进入动画的持续时间、延迟与速度曲线类型3.v-enter-to:进入动画的结束状态。在元素插入完成后的下一帧被添加 (也就是 v-enter-from 被移除的同时),在过渡或动画完成之后移除。4.v-leave-from:离开动画的起始状态。在离开过渡效果被触发时立即添加,在一帧后被移除5.v-leave-active:离开动画的生效状态。应用于整个离开动画阶段。在离开过渡效果被触发时立即添加,在过渡或动画完成之后移除。这个 class 可以被用来定义离开动画的持续时间、延迟与速度曲线类型。6.v-leave-to:离开动画的结束状态。在一个离开动画被触发后的下一帧被添加 (也就是 v-leave-from 被移除的同时),在过渡或动画完成之后移除。*/
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
.v-enter-active,.v-leave-active {  transition: opacity 0.5s ease;}.v-enter-from,.v-leave-to {  opacity: 0;}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2.Fragment

  • 在vue2中:组件必须有一个根标签
  • 在vue3中:组件可以没有根标签,内部会将多个标签包含在一个Fragment虚拟元素中
  • 好处:减少标签层级,减少内存占用

3.Teleport

  • 什么是Teleport? —— Teleport是一种能够将我们组件html结构移动到指定位置的技术(开发的时候非常有用)
//弹窗实现<script setup>import { ref,inject } from 'vue';let isShow = ref(false)</script><template>  <div>      <button @click="isShow = true">点我弹窗</button>      <teleport to="body"> //定位到body        <div class="mask" v-if="isShow">            <div class="dialog">                <h4>我是一个弹窗</h4>                <h5>内容</h5>                <h5>内容</h5>                <h5>内容</h5>                <button @click="isShow = false">关闭</button>            </div>        </div>      </teleport>  </div></template><style>.dialog{    width: 300px;    height: 300px;    text-align: center;    position: absolute;    top: 50%;    left: 50%;    transform: translate(-50%,-50%);    background-color: blueviolet;    margin: 0 auto;}.mask{    position: absolute;    top: 0;    left: 0;    bottom: 0;    right: 0;    background-color: rgba(0, 0, 0, 0.5);}</style>
  • 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

4.Suspense

<script setup>import { defineAsyncComponent } from 'vue'; //引入异步组件const ChildVue = defineAsyncComponent(()=> import('./components/Child.vue')) //这叫做动态引入//这种引入叫做异步引入,如果app不出来的话,那么Child组件也不会引入进来,有一个先后顺序// import ChildVue from './components/Child.vue'; //静态引入// 得等,等所有的组件加载完成之后app才会一起出现/** * Suspense这个标签,底层就内置了插槽,就可以解决异步引入有时候刷新先后出来慢的问题 * v-slot:default 表示默认的输出组件 * v-slot:fallback 表示如果页面加载的慢了,会优先展示这个内容,有点像刷新页面的时候数据回来的慢了,就加载一会儿*/</script><template>  <div class="app">    <h3>我是父组件</h3>    <Suspense>      <template v-slot:default>        <ChildVue></ChildVue>      </template>      <template v-slot:fallback>        <h3>稍等,加载中....</h3>      </template>    </Suspense>  </div></template><style>.app{  background-color: gray;  padding: 10px;  box-sizing: border-box;}</style>/**还有一种方法就是在子组件中,setup返回一个promise对象,这里之所以可以使用setup返回promise的原因是: 我们引入的是异步组件且使用了<Suspense></Suspense>*/
  • 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
  • 等待异步组件时渲染一些后备内容,获得更好的用户体验

八: 新的生命周期钩子

1.常见的生命周期钩子

onMounted()onUpdated()onUnmounted()onBeforeMount()onBeforeUpdate()onBeforeUnmount()onActivated()onDeactivated()onServerPrefetch()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2.新的生命周期钩子

//1.onErrorCaptured():注册一个钩子,在捕获了后代组件传递的错误时调用。function onErrorCaptured(callback: ErrorCapturedHook): voidtype ErrorCapturedHook = (  err: unknown,  instance: ComponentPublicInstance | null,  info: string) => boolean | void//2.onRenderTracked():注册一个调试钩子,当组件渲染过程中追踪到响应式依赖时调用。 function onRenderTracked(callback: DebuggerHook): voidtype DebuggerHook = (e: DebuggerEvent) => voidtype DebuggerEvent = {  effect: ReactiveEffect  target: object  type: TrackOpTypes /* 'get' | 'has' | 'iterate' */  key: any}//3.onRenderTriggered():注册一个调试钩子,当响应式依赖的变更触发了组件渲染时调用。function onRenderTriggered(callback: DebuggerHook): voidtype DebuggerHook = (e: DebuggerEvent) => voidtype DebuggerEvent = {  effect: ReactiveEffect  target: object  type: TriggerOpTypes /* 'set' | 'add' | 'delete' | 'clear' */  key: any  newValue?: any  oldValue?: any  oldTarget?: Map<any, any> | Set<any>}//4.onServerPrefetch():注册一个异步函数,在组件实例在服务器上被渲染之前调用。function onServerPrefetch(callback: () => Promise<any>): void/**补充:1.如果这个钩子返回了一个 Promise,服务端渲染会在渲染该组件前等待该 Promise 完成。      2.这个钩子仅会在服务端渲染中执行,可以用于执行一些仅存在于服务端的数据抓取过程*///试例:<script setup>import { ref, onServerPrefetch, onMounted } from 'vue'const data = ref(null)onServerPrefetch(async () => {  // 组件作为初始请求的一部分被渲染  // 在服务器上预抓取数据,因为它比在客户端上更快。  data.value = await fetchOnServer(/* ... */)})onMounted(async () => {  if (!data.value) {    // 如果数据在挂载时为空值,这意味着该组件    // 是在客户端动态渲染的。将转而执行    // 另一个客户端侧的抓取请求    data.value = await fetchOnClient(/* ... */)  }})</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
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62

九: 解决没有this + 各种api的方法

  • 在Vue2项目中可以使用this.$router.push等方法进行路由的跳转,但是在Vue3的setup函数里,并没有this这个概念,因此如何使用路由方法
// 在新的vue-router里面尤大加入了一些方法,比如这里代替this的useRouter,具体使用如下://引入路由函数import { useRouter } from "vue-router";//使用setup() {    //初始化路由    const router = useRouter();    router.push({        path: "/"    });        return {};}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 在vue2中可以通过this来访问到$refs,vue3中由于没有this所以获取不到了,但是官网中提供了方法来获取:
<template>  <h2 ref="root">姓名</h2></template><script>    //使用setup的注意事项    import { onMounted, ref } from 'vue'    export default {        name: 'test9',        setup(){            const root  = ref(null)            onMounted(()=>{                console.log(root.value);            })            return {                root            }        },    }</script>//第二种方法,也可以通过getCurrentInstance来获取<template>  <h2 ref="root">姓名</h2></template><script>    //使用setup的注意事项    import { onMounted, ref, getCurrentInstance } from 'vue'    export default {        name: 'test9',        setup(){)            const {proxy} = getCurrentInstance()            onMounted(()=>{                console.log(proxy.$refs.root);            })            return {            }        },    }</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
  • 关于element在vue3的使用方法,没有this.$message等方法解决方案
//关于element在vue3的使用方法,没有this.$message等方法解决方案<template>  <!-- 测试组件 -->  <button @click="doLogin">登录</button></template><script>import { getCurrentInstance } from 'vue'export default {  name: 'Test',  setup () {    const instance = getCurrentInstance() // vue3提供的方法,创建类似于this的实例    const doLogin = () => {      instance.proxy.$message({ type: 'error', text: '登录失败' }) // 类似于this.$message()    }    return { doLogin }  },   // 如果想试用this.$message,须在mounted钩子函数中,setup中没有this实例,   //但vue3.0中还是建议在setup函数中进行逻辑操作  mounted () {    this.$message({ type: 'error', text: '登录失败' })  }}</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
网站建设定制开发 软件系统开发定制 定制软件开发 软件开发定制 定制app开发 app开发定制 app开发定制公司 电商商城定制开发 定制小程序开发 定制开发小程序 客户管理系统开发定制 定制网站 定制开发 crm开发定制 开发公司 小程序开发定制 定制软件 收款定制开发 企业网站定制开发 定制化开发 android系统定制开发 定制小程序开发费用 定制设计 专注app软件定制开发 软件开发定制定制 知名网站建设定制 软件定制开发供应商 应用系统定制开发 软件系统定制开发 企业管理系统定制开发 系统定制开发