当前位置:首页 > 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推荐的组件封装方式。

<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>实现运行时切换组件,常用于标签页或条件渲染场景。

<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 倒计时组件实现 核心思路 通过 setInterval 或 setTimeout 实现时间递减,结合 Vue 的响应式数据更新 UI。需注意组件销毁时清除定时器。 基础实现方案 模板部分…

jquery的方法

jquery的方法

jQuery 常用方法分类 jQuery 是一个快速、简洁的 JavaScript 库,提供了大量简化 DOM 操作、事件处理、动画效果和 AJAX 交互的方法。以下是 jQuery 核心方法的分类和…

uniapp倒计时组件

uniapp倒计时组件

uniapp倒计时组件实现方法 使用内置组件实现 uniapp提供了<countdown>组件用于倒计时功能,支持自定义格式和样式。示例代码如下: <countdown…

vue实现广告组件

vue实现广告组件

vue实现广告组件的方法 使用动态组件实现 在Vue中可以通过动态组件的方式加载广告组件,根据不同的条件展示不同的广告内容。动态组件使用<component :is="currentCompon…

vue 实现组件刷新

vue 实现组件刷新

组件局部刷新 在Vue中实现组件刷新可以通过强制重新渲染组件来实现。常用的方法有以下几种: 使用v-if指令 通过切换v-if条件触发组件的销毁和重建 <template> &…

vue组件实现vmodel

vue组件实现vmodel

Vue 组件实现 v-model 在 Vue 中,v-model 是双向数据绑定的语法糖,默认情况下绑定 value 属性并监听 input 事件。在自定义组件中实现 v-model 需要正确配置 p…