vue3的基本使用(超详细)

2023-1-16    前端达人

一、初识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 'vue import 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 = 1 const 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 catch try{ Object.defineProperty( obj, 'c', { get(){ return 3 }, }) Object.defineProperty( obj, 'c', { get(){ return 4 }, }) } catch(error) { console.log(error) } //新的方式: 通过Reflect反射对象去操作,相对来说要舒服一点,不会要那么多的try catch const 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-setup import 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.js import {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 // string props.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

蓝蓝设计建立了UI设计分享群,每天会分享国内外的一些优秀设计,如果有兴趣的话,可以进入一起成长学习,请加蓝小助,微信号:ben_lanlan,报下信息,蓝小助会请您入群。欢迎您加入噢~~希望得到建议咨询、商务合作,也请与我们联系01063334945。


分享此文一切功德,皆悉回向给文章原作者及众读者.
免责声明:蓝蓝设计尊重原作者,文章的版权归原作者。如涉及版权问题,请及时与我们取得联系,我们立即更正或删除。


蓝蓝设计www.lanlanwork.com )是一家专注而深入的界面设计公司,为期望卓越的国内外企业提供卓越的UI界面设计、BS界面设计 、 cs界面设计 、 ipad界面设计 、 包装设计 、 图标定制 、 用户体验 、交互设计、 网站建设 平面设计服务UI设计公司、界面设计公司、UI设计服务公司、数据可视化设计公司、UI交互设计公司、高端网站设计公司、UI咨询、用户体验公司、软件界面设计公司

日历

链接

个人资料

蓝蓝设计的小编 http://www.lanlanwork.com

存档