Admin.Net第六章:前端Vue3开发指南
目录#
1. Vue3基础与Composition API#
1.1 Composition API概述#
Vue3引入的Composition API是一种新的组件逻辑组织方式,相比Options API更加灵活和可复用。
Options API vs Composition API:
<!-- Options API -->
<script>
export default {
data() {
return {
count: 0
}
},
computed: {
doubleCount() {
return this.count * 2
}
},
methods: {
increment() {
this.count++
}
}
}
</script>
<!-- Composition API -->
<script setup lang="ts">
import { ref, computed } from 'vue'
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
const increment = () => count.value++
</script>
1.2 响应式数据#
<script setup lang="ts">
import { ref, reactive, computed, watch, watchEffect } from 'vue'
// ref - 基本类型响应式
const count = ref(0)
const message = ref('Hello')
// reactive - 对象响应式
const user = reactive({
name: 'Admin',
age: 18,
email: 'admin@example.com'
})
// computed - 计算属性
const fullInfo = computed(() => {
return `${user.name} (${user.age}岁)`
})
// 可写计算属性
const firstName = computed({
get: () => user.name.split(' ')[0],
set: (val) => {
user.name = val + ' ' + user.name.split(' ')[1]
}
})
// watch - 侦听器
watch(count, (newVal, oldVal) => {
console.log(`count changed from ${oldVal} to ${newVal}`)
})
// 侦听多个源
watch([count, () => user.name], ([newCount, newName]) => {
console.log(`count: ${newCount}, name: ${newName}`)
})
// 深度侦听
watch(user, (newVal) => {
console.log('user changed', newVal)
}, { deep: true })
// watchEffect - 自动追踪依赖
watchEffect(() => {
console.log(`count is ${count.value}, user is ${user.name