vue3实现
Vue 3 实现方法
Vue 3 提供了多种方式来实现功能,以下是常见的几种方法:
组合式 API
import { ref, computed } from 'vue'
export default {
setup() {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return {
count,
doubleCount,
increment
}
}
}
选项式 API
export default {
data() {
return {
count: 0
}
},
computed: {
doubleCount() {
return this.count * 2
}
},
methods: {
increment() {
this.count++
}
}
}
使用 <script setup> 语法糖
<script setup>
import { ref, computed } from 'vue'
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
</script>
组件通信
- Props 和 Emits
// 父组件 <ChildComponent :msg="message" @update="handleUpdate" />
// 子组件
const props = defineProps(['msg']) const emit = defineEmits(['update'])function handleClick() { emit('update', newValue) }
```状态管理 使用 Pinia 进行状态管理:
// store/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
// 组件中使用
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
路由实现 使用 Vue Router:
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
})
生命周期钩子

import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
console.log('组件已挂载')
})
onUnmounted(() => {
console.log('组件已卸载')
})






