当前位置:首页 > 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实现穿梭框树组件

vue实现穿梭框树组件

Vue 穿梭框树组件实现 穿梭框树组件通常结合了树形结构和穿梭框功能,允许用户在左右两栏之间移动树节点数据。以下是基于 Vue 的实现方案: 核心功能设计 数据结构 树形数据通常采用嵌套结构,例如:…

java如何调用另一个类的方法

java如何调用另一个类的方法

调用另一个类的方法 在Java中调用另一个类的方法,通常需要创建该类的对象或直接通过类名调用(静态方法)。以下是几种常见的方式: 通过对象实例调用实例方法 创建一个目标类的对象,通过对象调用其方法。…

vue实现列表组件

vue实现列表组件

Vue 列表组件实现方法 基础列表渲染 使用 v-for 指令渲染数组数据,需配合 :key 提升性能: <template> <ul> <li v-for…

vue实现搜索组件

vue实现搜索组件

Vue 实现搜索组件的方法 基础搜索组件实现 创建基础搜索组件需要包含输入框和搜索按钮。在Vue中可以使用v-model绑定输入值,通过@click或@keyup.enter触发搜索。 <te…

vue 实现动态组件

vue 实现动态组件

Vue 动态组件的实现方法 在 Vue 中,可以通过 <component> 标签结合 is 属性实现动态组件切换。以下是具体实现方式: 使用 is 属性绑定组件名 <templ…