当前位置:首页 > VUE

Vue组件实现方法

2026-02-11 02:07:51VUE

Vue组件实现方法

选项式API(Options API)

使用datamethodsprops等选项定义组件,适合传统Vue 2.x项目或偏好结构化代码的场景。

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  },
  methods: {
    updateMessage() {
      this.message = 'Updated'
    }
  }
}
</script>

组合式API(Composition API)

通过setup()函数组织逻辑,适合Vue 3.x的复杂组件,支持更好的代码复用和类型推断。

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

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

单文件组件(SFC)

.vue文件包含<template><script><style>三部分,是Vue推荐的组件封装方式。

Vue组件实现方法

<template>
  <button class="btn">{{ label }}</button>
</template>

<script>
export default {
  props: ['label']
}
</script>

<style scoped>
.btn {
  color: red;
}
</style>

函数式组件

无状态组件,通过渲染函数(render function)直接返回虚拟DOM,适用于纯展示型组件。

export default {
  functional: true,
  render(h, { props }) {
    return h('div', props.text)
  }
}

动态组件

使用<component :is>实现运行时切换组件,常用于标签页或条件渲染场景。

Vue组件实现方法

<template>
  <component :is="currentComponent" />
</template>

<script>
import CompA from './CompA.vue'
import CompB from './CompB.vue'
export default {
  data() {
    return {
      currentComponent: 'CompA'
    }
  }
}
</script>

异步组件

通过defineAsyncComponent实现按需加载,优化应用启动性能。

import { defineAsyncComponent } from 'vue'
const AsyncComp = defineAsyncComponent(() => import('./Comp.vue'))

递归组件

组件调用自身实现树形结构,需设置name选项并添加终止条件。

<template>
  <div>
    {{ node.name }}
    <TreeNode v-for="child in node.children" :node="child" />
  </div>
</template>

<script>
export default {
  name: 'TreeNode',
  props: ['node']
}
</script>

标签: 组件方法
分享给朋友:

相关文章

vue实现组件

vue实现组件

Vue 组件实现基础 Vue 组件是可复用的 Vue 实例,用于封装 UI 和逻辑。通过 .vue 文件或直接注册组件实现。 单文件组件 (SFC) 示例 <template>…

vue实现水印组件

vue实现水印组件

Vue 水印组件实现 基础水印组件实现 创建一个基础水印组件,通过 props 接收文本、颜色、大小等参数: <template> <div class="watermark-…

uniapp 滑动组件

uniapp 滑动组件

uniapp 滑动组件实现方法 使用swiper组件 uniapp内置的swiper组件可以实现滑动效果,适用于轮播图或页面切换场景。 示例代码: <swiper :indicator-d…

组件elementui

组件elementui

ElementUI 简介 ElementUI 是一套基于 Vue.js 的桌面端组件库,由饿了么前端团队开发并开源。它提供了丰富的 UI 组件(如按钮、表单、表格等),适合快速构建企业级中后台产品。…

如何判断react组件

如何判断react组件

判断 React 组件的依据 React 组件的判断通常基于其定义方式、功能特性和代码结构。以下是几种常见的判断方法: 函数组件与类组件 函数组件是通过 JavaScript 函数定义的,接收 pr…

vue 实现toast组件

vue 实现toast组件

实现 Vue Toast 组件的方法 创建基础 Toast 组件 在 Vue 项目中创建一个基础 Toast 组件,通常包含消息内容和显示控制逻辑。 <template> <d…