1. API 风格
组合式API -> <script setup>
选项式API -> export default {
data() {
return { count: 0 }
}
methods: {
increment() { this.count++ }
}
}
2. 响应式基础
1. reactive: 对 string、number 和 boolean 这样的 原始类型 无效
2. ref: 对原始数据类型有效,遇到对象会自动转换为reactive
3. 计算属性 computed
接受一个函数,该函数返回一个值,如果响应式没有改变,该值会缓存,不会每次调用都计算
4. Class 与 Style 绑定
1. <div :class="{ active: isActive }"></div>
2. 绑定一个数组,<div :class="[activeClass, errorClass]"></div>
3. 绑定内联样式,<div :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
5. 条件渲染
1. <h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no </h1>
6. 列表渲染
1. <li v-for="item in items">
{{ item.message }}
</li>
7. 事件处理
1. <button @click="count++">Add 1</button>
8. 表单输入绑定
1. <p>Message is: {{ message }}</p>
<input v-model="message" placeholder="edit me" />
9. 生命周期钩子
1. onMounted 注册一个回调函数,在组件挂载完成后执行
2. onUpdated 注册一个回调函数,在组件因为响应式状态变更而更新其 DOM 树之后调用
3. onUnmounted 注册一个回调函数,在组件实例被卸载之后调用
4. onBeforeMount 注册一个钩子,在组件被挂载之前被调用
5. onBeforeUpdate 注册一个钩子,在组件即将因为响应式状态变更而更新其 DOM 树之前调用
6. onBeforeUnmount 注册一个钩子,在组件实例被卸载之前调用
7. onErrorCaptured 注册一个钩子,在捕获了后代组件传递的错误时调用
8. onRenderTracked 注册一个调试钩子,当组件渲染过程中追踪到响应式依赖时调用
10. 侦听器
1. watch(侦听的响应属性或者函数返回值,函数)
11. 传递 props
1. defineProps 一样,属于宏定义,不需要导出函数 是一个宏,不需要导入
2. defineProps(['title'])
3. 给组件导入值,<BlogPost title="My journey with Vue" />
12. 监听事件
<!-- defineEmits 和 defineProps 一样,属于宏定义,不需要导出函数 -->
<!-- parent.vue, 父组件 -->
const postFontSize = ref(1)
<div :style="{ fontSize: postFontSize + 'em' }">
<!-- 父组件可以通过 `v-on` 或 `@` 来选择性地监听子组件上抛的事件 -->
<blog @enlarge-text="postFontSize += 0.1" /> // 组件
</div>
<!-- BlogPost.vue, 子组件 -->
<template>
<div class="blog-post">
<button @click="$emit('enlarge-text')">Enlarge text</button>
</div>
</template>
<!-- 或者 -->
<!-- BlogPost.vue, 子组件 -->
const emitDefine = defineEmits(['enlarge-text'])
<template>
<div class="blog-post">
<button @click="emitDefine('enlarge-text')">Enlarge text</button>
</div>
</template>
13. 通过插槽来分配内容
<!-- 如下所示,我们使用 `<slot>` 作为一个占位符,父组件传递进来的内容就会渲染在这里 -->
<template>
<div class="alert-box">
<slot />
</div>
</template>
14. unref,toRef, toRefs, isRef
<!-- unref : 如果接受的参数是 ref 返回的值是 value, 否则直接返回参数本身 -->
<!-- 1. 参数: `(源对象 , 源对象属性)`
2. 可以用来为源响应式对象上的某个 property 新创建一个 ref。然后,
ref 可以被传递,它会保持对其源 property 的响应式连接。
3. 用人话讲就是为 源响应式对象(toRef的第一个参数) 上的某个 property 新创建一个 ref -->
// 新的ref对象对源property建立响应式连接,修改其中一个,另一个也会同步!
const state = reactive({
foo: 1,
bar: 2
})
const fooRef = toRef(state, 'foo')
fooRef.value++
state.foo++
console.log(fooRef,state) // 3
<!-- toRefs 原理:toRefs 会将 reactive 生成的对象的根级属性全都用 ref 转成
ref 对象,然后解构出来的都是 ref 对象,从而不丢失响应式 -->
const state = reactive({ foo: 1,bar: 2})
const stateAsRefs = toRefs(state)
<!-- stateAsRefs 是一个普通对象,stateAsRefs.foo则是响应式对象,
因此{...}解构才不会丢失响应式 -->
<!-- isRef:检查值是否为一个 ref 对象 -->