vue3笔记

Vue3快速上手

1.Vue3简介

2.Vue3带来了什么

1.性能的提升

  • 打包大小减少41%

  • 初次渲染快55%, 更新渲染快133%

  • 内存减少54%

    ……

2.源码的升级

  • 使用Proxy代替defineProperty实现响应式

  • 重写虚拟DOM的实现和Tree-Shaking

    ……

3.拥抱TypeScript

  • Vue3可以更好的支持TypeScript

4.新的特性

  1. Composition API(组合API)

    • setup配置
    • ref与reactive
    • watch与watchEffect
    • provide与inject
    • ……
  2. 新的内置组件

    • Fragment
    • Teleport
    • Suspense
  3. 其他改变

    • 新的生命周期钩子
    • data 选项应始终被声明为一个函数
    • 移除keyCode支持作为 v-on 的修饰符
    • ……

一、创建Vue3.0工程

1.使用 vue-cli 创建

官方文档:https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create

1
2
3
4
5
6
7
8
9
## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version
## 安装或者升级你的@vue/cli
npm install -g @vue/cli
## 创建
vue create vue_test
## 启动
cd vue_test
npm run serve

2.使用 vite 创建

官方文档:https://v3.cn.vuejs.org/guide/installation.html#vite

vite官网:https://vitejs.cn

  • 什么是vite?—— 新一代前端构建工具。
  • 优势如下:
    • 开发环境中,无需打包操作,可快速的冷启动。
    • 轻量快速的热重载(HMR)。
    • 真正的按需编译,不再等待整个应用编译完成。
  • 传统构建 与 vite构建对比图

1
2
3
4
5
6
7
8
## 创建工程
npm init vite-app <project-name>
## 进入工程目录
cd <project-name>
## 安装依赖
npm install
## 运行
npm run dev

二、常用 Composition API

官方文档: https://v3.cn.vuejs.org/guide/composition-api-introduction.html

1.setup(props, context)

  1. 理解:Vue3.0中一个新的配置项,值为一个函数。

  2. setup是所有Composition API(组合API)“ 表演的舞台 ”。

  3. 组件中所用到的 (props) 一定要在其他选项里配置才行

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    defineComponent(
    (props) => {
    return () => {
    return h('div', props.num)
    }
    },
    {
    props: {
    num: Number
    }
    }
    )
    • props的原理
      • 父组件的reactive通过props传递过来保持不变
      • 父组件的ref通过props传递过来会在解包
        • 而深层的ref底层是Prox
  4. setup函数的两种返回值:

    1. 若返回一个对象,则对象中的属性、方法, 在模板中均可以直接使用。(重点关注!)
    2. <span style="color:#aad">若返回一个渲染函数:则可以自定义渲染内容。(了解)
    3. 返回一个Proimse对象
    1
    2
    3
    4
    5
    //返回一个渲染函数
    import {h} from 'vue'
    setup() {
    return ()=> h('h1',"title")
    }
  5. <script setup> 语法糖

    • 可以与 <script>混用,但是script里面的setup()会失效

    • 直接写setup() 内部的内容

    • 自动return顶层绑定,

      1
      2
      const b = ref(2)
      defineExpose(b) //显示指定暴露给模板b
    • 如何接收props,slots, emits, 等等

      1
      2
      3
      4
      const props = defineProps({
      foo: String
      })
      const emit = defineEmits(['change', 'delete'])
  6. 注意点:

    1. 尽量不要与Vue2.x配置混用
      • Vue2.x配置(data、methos、computed…)中可以访问到setup中的属性、方法.但在setup中不能访问到Vue2.x配置(data、methos、computed…)。
      • 如果有重名, setup优先。
    2. setup可以是一个异步函数需要Suspense和异步引入组件的配合(详见Suspense)

2.setup的两个注意点

  • setup执行的时机

    • 在beforeCreate之前执行一次,this是undefined。
  • setup的参数

    • props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性

      1
      2
      3
      4
      5
      6
      7
      8
      //假设父组件给子组件传了 三个参数 
      <Son param1="param1" param2="param2" param3="param3">

      props: ['param1', 'param2']
      setup(props, context) {
      console.log(props) //可以接收到param1 和 param2 , 访问 props.param1
      console.log(context.attrs)//可以接收到param3, 访问 context.attrs.param3
      }
    • context:上下文对象

      • attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性, 相当于 this.$attrs
      • slots: 收到的插槽内容, 相当于 this.$slots
      • emit: 分发自定义事件的函数, 相当于 this.$emit

3.ref函数

  • 作用: 定义一个响应式的数据

  • 语法: const xxx = ref(initValue)

    • 创建一个包含响应式数据的引用对象(reference对象,简称ref对象
    • JS中操作数据: xxx.value
    • 模板中读取数据: 不需要.value,直接:
      ``
  • 备注:

    • 接收的数据可以是:基本类型、也可以是对象类型。

    • 基本类型的数据:响应式依然是靠 Object.defineProperty()getset完成的。

    • 对象、数组类型的数据:value值是调用 reactive函数

      • RefImpl {__v_isShallow: false, dep: undefined, __v_isRef: true, _rawValue: '123', _value: '123'}
            dep: undefined
            __v_isRef: true
            __v_isShallow: false
            _rawValue: "123"
            _value: "123"
            value: (...)
            [[Prototype]]: Object
        
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22

        ## 4.reactive函数

        - 作用: 定义一个`<strong style="color:#DD5145">`对象类型`</strong>`的响应式数据(基本类型不要用它,要用 ``ref``函数)
        - 语法:``const 代理对象= reactive(源对象)``接收一个对象(或数组),返回一个代理对象(Proxy的实例对象,简称proxy对象)
        - reactive定义的响应式数据是“深层次的”(可以相应通过下标修改的数组数据)
        - 内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据进行操作。

        ## 5.Vue3.0中的响应式原理

        ### vue2.x的响应式

        - 实现原理:

        - 对象类型:通过 ``Object.defineProperty()``对属性的读取、修改进行拦截(数据劫持)。
        - 数组类型:通过重写更新数组的一系列方法来实现拦截。(对数组的变更方法进行了包裹)。

        ```js
        Object.defineProperty(data, 'count', {
        get () {},
        set () {}
        })
  • 存在问题:

    • 新增属性、删除属性, 界面不会更新。
    • 直接通过下标修改数组, 界面不会自动更新。

Vue3.0的响应式

  • 实现原理:

  • Reflect

    • Reflect.get(target, propertyKey[, receiver])
      
      1
      2
      - ```js
      Reflect.set(target, propertyKey, value[, receiver])
    • Reflect.deleteProperty(target, propertyKey)
      
      1
      2
      3
      4
      5
      6
      7
      - .defineProperty()

      ```js
      let obj = {a:1, b:2}
      Reflect.defineProperty(obj, 'c', 3) //给obj添加一个c: 3,返回true
      Reflect.defineProperty(obj, 'c', 4) //不生效,会返回false
      //Object.defineProperty 会直接报错

6.reactive对比ref

  • 从定义数据角度对比:
    • ref用来定义:<strong style="color:#DD5145">基本类型数据</strong>
    • reactive用来定义:<strong style="color:#DD5145">对象(或数组)类型数据</strong>
    • 备注:ref也可以用来定义<strong style="color:#DD5145">对象(或数组)类型数据</strong>, 它内部会自动通过 reactive转为<strong style="color:#DD5145">代理对象</strong>
  • 从原理角度对比:
    • ref通过 Object.defineProperty()getset来实现响应式(数据劫持)。
    • reactive通过使用<strong style="color:#DD5145">Proxy</strong>来实现响应式(数据劫持), 并通过<strong style="color:#DD5145">Reflect</strong>操作<strong style="color:orange">源对象</strong>内部的数据。
  • 从使用角度对比:
    • ref定义的数据:操作数据<strong style="color:#DD5145">需要</strong>```.value``,读取数据时模板中直接读取不需要```.value``。
    • reactive定义的数据:操作数据与读取数据:<strong style="color:#DD5145">均不需要````.value``。

7.计算属性与监视

1.computed函数

  • 与Vue2.x中computed配置功能一致

  • 写法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    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]
    }
    })
    }

2.watch函数

  • 与Vue2.x中watch配置功能一致

  • 两个小“坑”:

    • 监视reactive定义的响应式数据中某个属性时:deep配置有效。
  • <text style="color:red">重要</text>

    • 默认情况下,侦听器回调会在父组件更新 (如有) 之后、所属组件的 DOM 更新之前被调用
    • flush: post 在组件渲染后执行
    1
    2
    3
    4
    const domNode = ref(null)
    watch(domNode,(value)=> {}, {flush: post})
    ...
    <div ref='domNode'></div>
  • watch 第一个参数可以是 getter, ref, proxy,

    • getter:
    1
    2
    3
    4
    watch(
    () => x.value + y.value,
    (sum) => console.log(`sum of x + y is: ${sum}`)
    )
    • ref:
      • 自动对x深层监听(因为ref有深层对象时底层调用reactive)
      • newValue自动解包
    1
    2
    3
    watch(x, (newValue) => {
    console.log(`x is ${newX}`)
    })
    • proxy:
      • 自动深层监听
      • 监听对象是proxy时,newVal 和 oldVal 是同一个对象
      • 只监听某个属性则要写成getter写法
        • getter不会自动开启deep
        • getter如果返回原始类型则 oldVal有效;
        • getter如果返回引用类型则 只有更改了对象或者开启deep才能监听到
    1
    2
    3
    4
    5
    const obj = reactive({count: 0})
    watch(obj, (newVal, oldVal) => {
    console.log(`count is: ${obj.newVal}`)
    })
    watch(()=>obj.count, ()=>{})

3.watchEffect函数

  • watch的套路是:既要指明监视的属性,也要指明监视的回调。

  • watchEffect的套路是:<u>不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性</u>

  • watchEffect有点像computed:

    • 但是watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值。
    • 默认开启immediate : true
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。
    const watch1 = watchEffect(()=>{
    const x1 = sum.value
    const x2 = person.age
    console.log('watchEffect配置的回调执行了')
    },{
    flush:'post' //Dom更新后触发侦听器回调
    })
    //停止侦听器
    watch1()

注意: 当依赖项改变后,先触发侦听器回调再触发update,所以侦听器回调访问到的是更新前的Dom

8.生命周期

vue3的生命周期 <img src="https://cn.vuejs.org/assets/lifecycle.16e4c08e.png" alt="lifecycle_2" />

  • Vue3.0中可以继续使用Vue2.x中的生命周期钩子—(选项式api),但有有两个被更名:
    • 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

9.自定义hook函数

  • 什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装

    1
    2
    3
    4
    5
    6
    // "/hook/useHook.js
    export default {
    // ... 一系列变量
    // ... 一系列方法
    return result;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    // "/app.vue/"
    import useHook from './hook/useHook.js'
    export default {
    setup() {
    // ...一系列操作
    const result = useHook(); //接收过来了
    return {result} //可以放到模板里
    }
    }

10.toRef

  • 作用:创建一个 ref 对象,其value值指向另一个对象中的某个属性。

  • 语法:const name = toRef(person,'propName')

  • 应用: 要将响应式对象中的某个属性单独提供给外部使用时。

  • 扩展:toRefstoRef功能一致,但可以批量创建多个 ref 对象,语法:toRefs(person)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    setup() {
    let obj = {
    key1: 1,
    key2: 2,
    key3: 3
    }
    return {
    ...toRefs(obj)//把所有属性暴露给模板
    }
    }
    //torefs(obj)
    {key1: ObjectRefImpl, key2: ObjectRefImpl, key3: ObjectRefImpl}
    key1: ObjectRefImpl {_object: Proxy(Object), _key: 'key1', _defaultValue: undefined, __v_isRef: true}

    key2: ObjectRefImpl {_object: Proxy(Object), _key: 'key2', _defaultValue: undefined, __v_isRef: true}

    key3: ObjectRefImpl {_object: Proxy(Object), _key: 'key3', _defaultValue: undefined, __v_isRef: true}

    [[Prototype]]: Object

11.ref引用

1
2
3
4
5
6
7
8
<template>
<input ref="inputRef">
</template>
<script setup>
import {ref} from 'vue'
//inputRef.value ===> input元素的引用
const inputRef = ref(null)
</script>

####在v-for的标签上使用ref引用

1
2
3
4
5
6
<ul>
<!-- 获得元素数组 -->
<li v-for="item in list" ref="itemRefs">
{{ item }}
</li>
</ul>

在组件上使用ref引用

  1. 获得组件实例
  2. 如果子组件用了 <script setup>,则默认组件私有,得不到任何东西。
    1. 可以在子组件中 defineExpose({})宏显式暴露

12.定义组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//方式一
import { ref } from 'vue'

export default {
setup() {
const count = ref(0)
return { count }
},
template: `
<button @click="count++">
You clicked me {{ count }} times.
</button>`
// 也可以针对一个 DOM 内联模板:
// template: '#my-template-element'
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//方式二
export default defineComponent({
name: "button-counter",
props: ["count"],
methods: {
onClick() {
this.$emit("change", this.count + 1);
}
},
render() {
// console.log("render.this", this) //指向vc
return (
<button onClick={this.onClick}>数量 {this.count}+</button>
);
}
})

动态组件 :is

1
<component :is="被注册的组件名、导入的组件对象"></component>

is的另一种用法

1
2
3
<table>
<tr is="vue:blog-post-row"></tr>
</table>

注册组件

1
2
import componentName from './component/componentName'
app.component('componentName',componentName)

13.传递props

1
2
3
4
5
<script setup>
//defineProps来接收父组件props
const props = defineProps(['title'])
//props.title 使用
</script>

14.自定义事件

同vue2

15. 路由

配置

  1. npm i vue-router@4
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    2. ```js
    // 在src/router/index.js
    import { createRouter,createWebHashHistory } from "vue-router";

    const routes = [{
    path: '/',
    name: 'index',
    component: App
    }]

    const router = createRouter({
    history:createWebHashHistory(),
    routes
    })

    export default router
  2. //在 main.js
    import router from './router'
    ...
    app.use(router)
    ...
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12

    #### 使用

    ```vue
    <script setup>
    import { useRouter } from 'vue-router'
    const router = useRouter()
    ...
    const gotoAbout = () => {
    router.push('/about')
    }
    </script>

三、其它 Composition API

1.shallowReactive 与 shallowRef

  • shallowReactive:只处理对象最外层属性的响应式(浅响应式)。

  • shallowRef:只处理基本数据类型的响应式, 不进行对象的响应式处理。

  • 什么时候使用?

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

2.readonly 与 shallowReadonly

  • readonly: 让一个响应式数据变为只读的(深只读)。
  • shallowReadonly:让一个响应式数据变为只读的(浅只读)。
  • 应用场景: 不希望数据被修改时。

3.toRaw 与 markRaw

  • toRaw:
    • 作用:将一个由 reactive生成的响应式对象转为普通对象
    • 使用场景:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作,不会引起页面更新。
  • markRaw:
    • 作用:标记一个对象,使其永远不会再成为响应式对象
    • 应用场景:
      1. 有些值不应被设置为响应式的,例如复杂的第三方类库等。
      2. 当渲染具有不可变数据源的大列表时,跳过响应式转换可以提高性能。

4.customRef

  • 作用:创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制。

  • 实现防抖效果:

    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
    <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>

5.provide 与 inject

  • 底层:不做任何处理直接提供引用 (与props不同)

  • 作用:实现祖与后代组件间通信

  • 套路:父组件有一个 provide 选项来提供数据,后代组件有一个 inject 选项来开始使用这些数据

  • 具体写法:

    1. 祖组件中:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      setup(){
      ......
      let car = reactive({name:'奔驰',price:'40万'})
      let something = ref("hello")

      provide('car',car) //分别是 *注入名 *注入属性(可以是响应式的)
      provide('something', something) //不需要something.value
      ......
      }
    2. 后代组件中:

      1
      2
      3
      4
      5
      6
      7
      setup(props,context){
      ......
      const car = inject('car' [,default]) //按照注入名来接收, 可以有默认值
      const something = inject('something')
      return {car, something}
      ......
      }

6.响应式数据的判断

  • isRef: 检查一个值是否为一个 ref 对象

  • isReactive: 检查一个对象是否是由 reactive 创建的响应式代理

  • isReadonly: 检查一个对象是否是由 readonly 创建的只读代理

  • isProxy: 检查一个对象是否是由 reactive 或者 readonly 方法创建的代理

    1
    2
    3
    4
    let arr = ref([1,2,3])
    isProxy(arr) //false
    isProxy(arr.value) // true !
    //说明对象类型的ref的value是借助reactive实现,而reactive用到了Proxy

四、Composition API 的优势

1.Options API 存在的问题

使用传统OptionsAPI中,新增或者修改一个需求,就需要分别在data,methods,computed里修改 。

2.Composition API 的优势

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

五、新的组件

1.Fragment

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

2.Teleport

  • 什么是Teleport?—— Teleport 是一种能够将我们的组件html结构移动到指定位置的技术。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <!-- 可以写css选择器 -->
    <teleport to="body"> <!-- 移动到body标签里的最下面 -->
    <div v-if="isShow" class="mask">
    <div class="dialog">
    <h3>我是一个弹窗</h3>
    <button @click="isShow = false">关闭弹窗</button>
    </div>
    </div>
    </teleport>

3.Suspense

  • 等待异步组件时渲染一些额外内容,让应用有更好的用户体验

  • 使用步骤:

    • 异步引入组件

      1
      2
      import {defineAsyncComponent} from 'vue'
      const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
    • 使用 Suspense包裹组件,并配置好 defaultfallback

      • Suspense组件内部有两个 具名插槽,分别表示需要 正常展示的内容和 没有加载出来时的内容
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      <template>
      <div class="app">
      <h3>我是App组件</h3>
      <Suspense>
      <template v-slot:default>
      <Child/>
      </template>
      <template v-slot:fallback>
      <h3>加载中.....</h3>
      </template>
      </Suspense>
      </div>
      </template>
    • setup返回promise对象

      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
      //1. 父组件必须异步引入子组件
      //2. 父组件必需
      <Suspense>
      <Child><Child/>
      <Suspense/>
      //2. 子组件中
      setup () {
      let count = ref(0);
      //setup 返回一个Pormise对象,其中PromiseResult是RefImpl对象
      return new Promise((resolve)=> {
      setTimeout(() => {
      resolve({count}) //! count要用{}包裹
      }, 1200);
      })
      }
      }
      //另一种
      async setup() {
      let count = ref(0);
      let asyncCount = new Promise((resolve) => {
      setTimeout(() => {
      resolve({ count })
      }, 500);
      })
      // console.log(await asyncCount) //{count: RefImpl}
      return await asyncCount
      //返回不了??? => 看上一行,是count, 所以模板里面不要用asyncCount
      }

3.KeepAlive

  • 多个组件间动态切换时缓存被移除的组件实例
1
2
3
<KeepAlive>
<component :is="activeComponent" />
</KeepAlive>

六、其他

1.全局API的转移

  • Vue 2.x 有许多全局 API 和配置。

    • 例如:注册全局组件、注册全局指令等。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      //注册全局组件
      Vue.component('MyButton', {
      data: () => ({
      count: 0
      }),
      template: '<button @click="count++">Clicked {{ count }} times.</button>'
      })

      //注册全局指令
      Vue.directive('focus', {
      inserted: el => el.focus()
      }
  • 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
1
2
3
4
5
//main.js
create(App).mount("#app")
//修改为
const app = create(App) //此时拿到了app
app.mount("#app")

2.其他改变

  • data选项应始终被声明为一个函数。

  • 过度类名的更改:

    • Vue2.x写法

      1
      2
      3
      4
      5
      6
      7
      8
      .v-enter,
      .v-leave-to {
      opacity: 0;
      }
      .v-leave,
      .v-enter-to {
      opacity: 1;
      }
    • Vue3.x写法

      1
      2
      3
      4
      5
      6
      7
      8
      9
      .v-enter-from,
      .v-leave-to {
      opacity: 0;
      }

      .v-leave-from,
      .v-enter-to {
      opacity: 1;
      }
  • 移除keyCode作为 v-on 的修饰符,同时也不再支持 config.keyCodes

    1
    2
    Vue.config.keyCodes.huiche = 13
    <p @keydown.13="fn">asd<p/>
  • 移除 v-on.native修饰符

    • 父组件中绑定事件

      1
      2
      3
      4
      <my-component
      v-on:close="handleComponentEvent"
      v-on:click="handleNativeClickEvent"
      />
    • 子组件中声明自定义事件

      1
      2
      3
      4
      5
      <script>
      export default {
      emits: ['close'] //接收了close代表是自定义事件,没接收的click代表是原生事件
      }
      </script>
  • 移除过滤器(filter)

    过滤器虽然这看起来很方便,但它需要一个自定义语法,打破大括号内表达式是 “只是 JavaScript” 的假设,这不仅有学习成本,而且有实现成本!建议用方法调用或计算属性去替换过滤器。

  • ……

七、pinia

1.storeToRefs

  • 只需要响应式state时使用
1
2
3
4
5
6
7
8
9
10
<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
// `name` 和 `doubleCount` 是响应式的 ref
// 同时通过插件添加的属性也会被提取为 ref
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { name, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store
</script>

2.$reset() – 仅选项式可用

  • 重置为初始值
  • 仅选项式可用
1
2
const store = useStore()
store.$reset()

3.$patch

  • 同时修改多个属性
1
2
3
4
store.$patch((state) => {
state.items.push({ name: 'shoes', quantity: 1 })
state.hasChanged = true
})
  • 替换属性
1
2
3
4
// 这实际上并没有替换`$state`
store.$state = { count: 24 }
// 在它内部调用 `$patch()`:
store.$patch({ count: 24 })

八、Vue for Typescript

为props标注类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
在泛型里标注
<script setup lang="ts">
//写法一:
const props = defineProps<{
foo: string
bar?: number
}>()

//写法二:抽成接口
interface Props {
foo: string
bar?: number
}
const props = defineProps<Props>()

// 解构默认值
const props =
</script>

解构默认值

1
2
3
4
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
})

为emits标注类型

1
2
3
4
5
const emit = defineEmits<{
change: [id: number]
update: [value: string]
//自定义事件名: [参数名: 类型]
}

为ref标注

1
const year = ref<string | number>('2020')

注意:

1
2
// 推导得到的类型:Ref<number | undefined>
const n = ref<number>()

为reactive标注

1
2
3
4
5
6
7
//以接口的形式
interface Book {
title: string
year?: number
}

const book: Book = reactive({ title: 'Vue3' })

为computed() 标注

1
2
//以泛型的方式
const double = computed<number>(() => {})

为事件处理函数标注

1
2
3
4
//该函数是事件处理调用的函数
function handleChange(event: Event) {
console.log((event.target as HTMLInputElement).value)
}

为provide/ inject 函数标注类型

1
2
3
4
5
6
7
8
9
10
11
12
//1. 创建一个 /provision/index.ts
import type { InjectionKey } from 'vue'
const key = Symbol() as InjectionKey<string>

export default key

//2. 父组件的setup里
import key from './provisions/index'
provide(key, "I'm from App.vue by provide")

//3. 子组件
const inj = inject<string>(key)

其他

样式作用到全局

1
2
:global(body ) {
}

triggerRef() 触发shallowRef的内部变量的副作用

1
2
3
4
5
6
7
8
9
const state: ShallowRef = shallowRef({count: 0})
watch(state, (val)=>console.log(val))

state.value.count++
triggerRef(state);




app.directive

全局指令必须在app.mount之前注册!