vue3实现写法
以下是 Vue 3 的核心实现写法示例,涵盖组合式 API、响应式数据、组件通信等常见场景:
组合式 API 基础写法
<script setup>
import { ref, reactive, computed, watch } from 'vue'
// 响应式数据
const count = ref(0)
const state = reactive({ name: 'Vue 3', version: 3.2 })
// 计算属性
const doubleCount = computed(() => count.value * 2)
// 方法
const increment = () => {
count.value++
}
// 监听器
watch(count, (newVal) => {
console.log(`count changed to ${newVal}`)
})
</script>
<template>
<button @click="increment">Count: {{ count }}</button>
<p>Double: {{ doubleCount }}</p>
<p>State: {{ state.name }} {{ state.version }}</p>
</template>
组件通信
父组件向子组件传值:
<!-- Parent.vue -->
<template>
<Child :msg="message" @update="handleUpdate"/>
</template>
<script setup>
import Child from './Child.vue'
const message = ref('Hello from parent')
const handleUpdate = (val) => {
message.value = val
}
</script>
<!-- Child.vue -->
<script setup>
defineProps(['msg'])
defineEmits(['update'])
</script>
<template>
<p>{{ msg }}</p>
<button @click="$emit('update', 'New value')">Update</button>
</template>
生命周期钩子
<script setup>
import { onMounted, onUpdated } from 'vue'
onMounted(() => {
console.log('组件挂载完成')
})
onUpdated(() => {
console.log('组件更新完成')
})
</script>
状态管理(Pinia)
// store/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
// 组件中使用
<script setup>
import { useCounterStore } from '@/store/counter'
const counter = useCounterStore()
</script>
<template>
<button @click="counter.increment">{{ counter.count }}</button>
</template>
路由管理(Vue Router)
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
// 组件内使用
<script setup>
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const goAbout = () => {
router.push('/about')
}
</script>
这些示例涵盖了 Vue 3 开发中的主要技术点,实际项目通常会结合这些模式进行开发。注意 <script setup> 是 Vue 3.2+ 推荐的语法糖,可简化组合式 API 的写法。



