深入理解Vue3 Composition API,掌握响应式编程
Vue3 Composition API详解
本文将深入介绍Vue3 Composition API的使用方法和最佳实践,帮助你更好地组织Vue3项目代码。
响应式基础
- ref和reactive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import { ref, reactive } from 'vue'
// ref用于基本类型
const count = ref(0)
console.log(count.value) // 0
// reactive用于对象
const state = reactive({
user: {
name: 'John',
age: 20
}
})
console.log(state.user.name) // John
|
- computed属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import { ref, computed } from 'vue'
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
// 可写的计算属性
const fullName = computed({
get() {
return firstName.value + ' ' + lastName.value
},
set(newValue) {
[firstName.value, lastName.value] = newValue.split(' ')
}
})
|
生命周期钩子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import { onMounted, onUpdated, onUnmounted } from 'vue'
export default {
setup() {
onMounted(() => {
console.log('组件已挂载')
})
onUpdated(() => {
console.log('组件已更新')
})
onUnmounted(() => {
console.log('组件已卸载')
})
}
}
|
监听器
- watch
1
2
3
4
5
6
7
8
9
10
11
12
|
import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newValue, oldValue) => {
console.log(`count从${oldValue}变为${newValue}`)
})
// 监听多个数据源
watch([count, message], ([newCount, newMessage], [oldCount, oldMessage]) => {
console.log('数据变化了')
})
|
- watchEffect
1
2
3
4
5
6
7
8
|
import { watchEffect, ref } from 'vue'
const count = ref(0)
const message = ref('Hello')
watchEffect(() => {
console.log(`count: ${count.value}, message: ${message.value}`)
})
|
组合式函数
- 提取可复用逻辑
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
|
// useCounter.js
import { ref, computed } from 'vue'
export function useCounter(initialValue = 0) {
const count = ref(initialValue)
const double = computed(() => count.value * 2)
function increment() {
count.value++
}
function decrement() {
count.value--
}
return {
count,
double,
increment,
decrement
}
}
// 使用组合式函数
import { useCounter } from './useCounter'
export default {
setup() {
const { count, double, increment } = useCounter(10)
return { count, double, increment }
}
}
|
- 异步处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
// useFetch.js
import { ref } from 'vue'
export function useFetch(url) {
const data = ref(null)
const error = ref(null)
const loading = ref(true)
fetch(url)
.then(res => res.json())
.then(json => data.value = json)
.catch(err => error.value = err)
.finally(() => loading.value = false)
return { data, error, loading }
}
|
依赖注入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 父组件
import { provide } from 'vue'
export default {
setup() {
provide('theme', 'dark')
provide('user', {
name: 'John',
role: 'admin'
})
}
}
// 子组件
import { inject } from 'vue'
export default {
setup() {
const theme = inject('theme')
const user = inject('user')
return { theme, user }
}
}
|
模板引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import { ref, onMounted } from 'vue'
export default {
setup() {
const inputRef = ref(null)
onMounted(() => {
inputRef.value.focus()
})
return { inputRef }
}
}
<template>
<input ref="inputRef" />
</template>
|
状态管理
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
|
// store.js
import { reactive } from 'vue'
export const store = {
state: reactive({
count: 0,
user: null
}),
increment() {
this.state.count++
},
setUser(user) {
this.state.user = user
}
}
// 组件中使用
import { store } from './store'
export default {
setup() {
return {
state: store.state,
increment: store.increment
}
}
}
|
最佳实践
- 代码组织
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
// 按功能组织代码
export default {
setup() {
// 用户状态
const { user, updateUser } = useUser()
// 表单处理
const { form, submitForm } = useForm()
// 页面逻辑
const { loading, refresh } = usePage()
return {
user,
updateUser,
form,
submitForm,
loading,
refresh
}
}
}
|
- 性能优化
1
2
3
4
5
6
7
|
import { shallowRef, markRaw } from 'vue'
// 使用shallowRef优化大型对象
const data = shallowRef(largeObject)
// 使用markRaw避免不必要的响应式
const router = markRaw(createRouter())
|
掌握这些Vue3 Composition API的使用方法,将帮助你写出更清晰、可维护的Vue3应用。