当前位置:首页 > VUE

Vue函数实现

2026-03-27 20:36:05VUE

Vue 函数式组件实现

函数式组件在 Vue 中是一种无状态(无 data)和无实例(无 this 上下文)的组件形式,通常用于性能优化或简单渲染逻辑。

定义函数式组件

// 方式1:通过 functional 选项
export default {
  functional: true,
  render(h, context) {
    return h('div', context.props.text)
  }
}

使用 setup 函数(Vue 3)

import { h } from 'vue'

export default {
  setup(props) {
    return () => h('div', props.text)
  }
}

高阶函数封装

利用工厂函数生成可复用的逻辑:

function withLoading(WrappedComponent) {
  return {
    data() {
      return { isLoading: false }
    },
    methods: {
      showLoading() { this.isLoading = true },
      hideLoading() { this.isLoading = false }
    },
    render(h) {
      return h(WrappedComponent, {
        props: {
          ...this.$props,
          loading: this.isLoading
        }
      })
    }
  }
}

组合式函数(Vue 3)

使用 composables 实现逻辑复用:

Vue函数实现

// useCounter.js
import { ref } from 'vue'

export function useCounter(initialValue = 0) {
  const count = ref(initialValue)
  const increment = () => count.value++
  return { count, increment }
}

// 组件中使用
import { useCounter } from './useCounter'

export default {
  setup() {
    const { count, increment } = useCounter()
    return { count, increment }
  }
}

渲染函数注意事项

  • 使用 h() 函数创建虚拟节点
  • 事件监听需通过 on 前缀指定,如 onClick
  • 插槽内容通过 context.slots() 访问
render(h) {
  return h('button', {
    on: {
      click: this.handleClick
    }
  }, this.$slots.default)
}

标签: 函数Vue
分享给朋友:

相关文章

jquery函数

jquery函数

jQuery 函数概述 jQuery 是一个快速、简洁的 JavaScript 库,通过封装原生 JavaScript 功能,简化 DOM 操作、事件处理、动画和 AJAX 等任务。其核心函数 $()…

Vue实现几行滚动

Vue实现几行滚动

Vue实现多行滚动效果 实现多行滚动效果可以通过CSS结合Vue的动态绑定完成。以下是几种常见实现方式: CSS动画实现 <template> <div class="scr…

Vue前端路由实现

Vue前端路由实现

Vue前端路由的实现方式 Vue前端路由通常通过vue-router库实现,它是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。以下是核心实现方法和步骤: 安装vue-router 通过…

Vue 实现左右滑动

Vue 实现左右滑动

Vue 实现左右滑动的方法 使用 touch 事件监听 通过监听 touchstart、touchmove 和 touchend 事件实现基础滑动逻辑。在 Vue 组件中声明这些事件处理函数,计算滑动…

Vue 实现下载

Vue 实现下载

Vue 实现文件下载的方法 前端下载(纯前端生成文件) 适用于需要动态生成文件内容并下载的场景,如导出表格数据为 CSV 或 Excel。 // 创建 Blob 对象并触发下载 const dow…

vue实现函数曲线

vue实现函数曲线

Vue 实现函数曲线的方法 在 Vue 中实现函数曲线通常需要结合 HTML5 的 Canvas 或 SVG 技术,以及 JavaScript 的数学计算能力。以下是几种常见的方法: 使用 Canv…