当前位置:首页 > VUE

vue3实现

2026-01-17 13:58:16VUE

以下是 Vue 3 实现常见功能的几种方法,涵盖基础到进阶场景:

组件基础实现

使用 setup 语法糖组合式 API:

<template>
  <button @click="increment">{{ count }}</button>
</template>

<script setup>
import { ref } from 'vue'
const count = ref(0)
const increment = () => count.value++
</script>

状态管理

Pinia 替代 Vuex 的推荐方案:

// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  actions: {
    increment() {
      this.count++
    }
  }
})

路由控制

Vue Router 4.x 基本配置:

import { createRouter, createWebHistory } from 'vue-router'
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About }
]
const router = createRouter({
  history: createWebHistory(),
  routes
})

响应式数据处理

深度响应式转换:

import { reactive } from 'vue'
const state = reactive({
  user: {
    name: 'John',
    contacts: [
      { type: 'email', value: 'john@example.com' }
    ]
  }
})

生命周期钩子

组合式 API 生命周期示例:

import { onMounted, onUnmounted } from 'vue'
onMounted(() => {
  console.log('组件挂载完成')
  window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

组件通信

父子组件通信:

<!-- 父组件 -->
<Child :msg="parentMsg" @update="handleUpdate"/>

<!-- 子组件 -->
<script setup>
defineProps(['msg'])
defineEmits(['update'])
</script>

动态组件加载

<component :is="currentComponent"/>
<script setup>
import { shallowRef } from 'vue'
const currentComponent = shallowRef(ComponentA)
</script>

自定义指令

全局指令注册:

const app = createApp(App)
app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

组合式函数复用

抽离可复用逻辑:

// useMouse.js
import { ref, onMounted, onUnmounted } from 'vue'
export function useMouse() {
  const x = ref(0)
  const y = ref(0)

  const update = (e) => {
    x.value = e.pageX
    y.value = e.pageY
  }

  onMounted(() => window.addEventListener('mousemove', update))
  onUnmounted(() => window.removeEventListener('mousemove', update))

  return { x, y }
}

Teleport 传送门

将内容渲染到 DOM 其他位置:

vue3实现

<teleport to="body">
  <div class="modal">传送的内容</div>
</teleport>

以上示例展示了 Vue 3 的核心功能实现方式,根据具体需求可进行组合和扩展。

分享给朋友:

相关文章

vue实现多级弹窗

vue实现多级弹窗

Vue 多级弹窗实现方法 方法一:使用动态组件与递归组件 在 Vue 中可以通过动态组件配合递归组件实现多级弹窗。定义一个基础弹窗组件,通过递归调用自身实现层级嵌套。 基础弹窗组件模板示例: &…

vue实现div

vue实现div

Vue 实现 DIV 元素的方法 在 Vue 中实现 DIV 元素可以通过多种方式,以下是几种常见的实现方法: 使用模板语法 在 Vue 的模板中直接使用 HTML 的 <div> 标签…

vue交互实现

vue交互实现

Vue 交互实现方法 Vue.js 提供了多种方式实现用户交互,包括事件处理、表单绑定、动态渲染等。以下是常见的交互实现方法: 事件处理 通过 v-on 或 @ 指令绑定事件,触发方法或直接执行表达…

vue 动画实现

vue 动画实现

Vue 动画实现方式 Vue 提供了多种方式实现动画效果,主要分为内置组件和第三方库集成。 使用 Vue 内置过渡组件 Vue 的 <transition> 和 <transiti…

vue实现slot

vue实现slot

Vue 中的 Slot 实现方法 Vue 的 slot 是一种内容分发机制,允许父组件向子组件插入内容。以下是几种常见的 Slot 实现方式: 默认 Slot 子组件通过 <slot>…

vue实现视频

vue实现视频

Vue 实现视频播放的方法 在 Vue 项目中实现视频播放可以通过多种方式完成,以下是几种常见的方法: 使用 HTML5 的 <video> 标签 在 Vue 组件中直接使用 HTML…