当前位置:首页 > VUE

vue3实现写法

2026-02-21 01:18:24VUE

以下是 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 的写法。

vue3实现写法

标签: 写法
分享给朋友:

相关文章

jquery写法

jquery写法

jQuery 基础语法与常用方法 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。以下是 jQuery 的基本写法和常用操作。…

uniapp组件写法

uniapp组件写法

uniapp组件的基本结构 在uniapp中创建组件通常需要遵循Vue单文件组件(SFC)规范。一个典型的组件文件包含<template>、<script>和<style…