Skip to content

Vue3 Cheatsheet

Helloworld

js
import { ref, reactive } from 'vue'

setup() {
    const count = ref(0);
    const increment = () => {
      count.value++;
    }

    const state = reactive({
        message: 'Hello',
        count: 0
    })

    onMounted(() => {
      console.log('Component mounted');
    });

    return {
        count,
        increment,
        state,
    }
}
  • setup:组件初始化时执行,返回的对象可以直接用于模版
  • ref
    • 在模版中支持自动解包
  • reactive:直接操作其属性即可触发视图更新
  • onMounted:在组件挂载后执行

响应式基础

  • ref:由于 reactive 的局限性,建议使用 ref 作为声明响应式状态的主要 API
  • nextTick:要等待 DOM 更新完成后再执行额外的代码,可以使用 nextTick
  • reactive 的局限性
    • 只能用于对象类型(对象、数组、Map 和 Set 等)
    • 不能替换整个对象
    • 解构不友好

组合式 API 风格

<script setup>

推荐 代码更简洁

js
<script setup>
import { ref } from 'vue';

const count = ref(0);
const increment = () => {
  count.value++;
};
</script>

<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>

setup()

js
<script>
import { ref } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const increment = () => {
      count.value++;
    };

    return { count, increment };
  }
};
</script>

<template>
  <button @click="increment">Count is: {{ count }}</button>
</template>

模版语法

动态绑定

包括属性绑定、样式绑定、类名绑定

不同于双向绑定,++动态绑定的数据的变化会影响视图,但视图的变化不会影响数据模型++,可通过开发者工具验证

js
<template>
    <!-- 绑定属性 -->
    <img :src="imageUrl" alt="Dynamic Image" />

    <!-- 绑定样式 -->
    <div :style="{ color: textColor, fontSize: fontSize + 'px' }">
        Styled Text
    </div>

    <!-- 绑定类名 -->
    <div :class="{ active: isActive, 'text-success': isSuccess }">
        Dynamic Classes
    </div>
</template>

双向绑定

  • v-model 指令:表单输入
  • 动态绑定和双向绑定的区别
Col1双向绑定动态绑定
数据流数据 <--> 视图数据 -> 视图
用法表单输入绑定 HTML 元素的属性、样式、类名等

JS 表达式

  • NO 三目运算符
  • 动态绑定 + 模版字符串
js
<div :id="`list-${id}`"></div>

内置指令

  • v-html
  • v-slot TODO
  • v-if
  • v-for
  • v-show
  • v-on 事件监听
  • v-bind 动态绑定

其它:

  • 修饰符 Modifiers <form @submit.prevent="onSubmit">...</form>
  • v-show 适合频繁切换
  • 当 v-if 和 v-for 同时存在于一个元素上的时候,v-if 会首先被执行

自定义指令

TODO

计算属性

使用 computed 替换 JS 表达式,计算属性具备缓存,性能更好

Bad

js
<p>Has published books:</p>
<span>{{ author.books.length > 0 ? 'Yes' : 'No' }}</span>

Good

js
<script setup>
import { reactive, computed } from 'vue'

const author = reactive({
  name: 'John Doe',
  books: [
    'Vue 2 - Advanced Guide',
    'Vue 3 - Basic Guide',
    'Vue 4 - The Mystery'
  ]
})

// 一个计算属性 ref
const publishedBooksMessage = computed(() => {
  return author.books.length > 0 ? 'Yes' : 'No'
})
</script>

<template>
  <p>Has published books:</p>
  <span>{{ publishedBooksMessage }}</span>
</template>

监听器

watch 可执行异步操作等副作用

单个 ref

js
watch(x, (newX) => {
  console.log(`x is ${newX}`);
});

getter 函数

js
// 不能直接侦听响应式对象的属性值
// 而是需要用一个返回该属性的 getter 函数
watch(
  () => x.value + y.value,
  (sum) => {
    console.log(`sum of x + y is: ${sum}`);
  }
);
js
watch(question, async (newQuestion, oldQuestion) => {
  console.log(`new: ${newQuestion} old: ${oldQuestion}`);
});

生命周期钩子

  1. setup
  2. onBeforeMount
  3. onMounted
  4. onBeforeUnmount

Mixins

TODO

组合式函数

use...

VueRouter

TODO

Vuex

TODO

开发工具

Vue Devtools

TODO

Vue CLI

TODO

Vite

内置 SCSS 支持

bash
npm install sass --save-dev

TODO

  • defineComponent
  • 常犯的错误:在 Vue 中,响应式数据的破坏通常是由于不遵循 Vue 的响应式机制,或者修改数据的方式不适合 Vue 的响应式系统。下面是一些常见的场景,说明为什么会破坏响应式数据,以及正确的做法。
  • Web Skill Box Model 等