当前位置:首页 > VUE

vue实现组件

2026-03-07 16:24:00VUE

Vue 实现组件的方法

单文件组件 (SFC)

使用 .vue 文件格式,包含 <template><script><style> 三个部分:

<template>
  <div class="example">{{ msg }}</div>
</template>

<script>
export default {
  data() {
    return {
      msg: 'Hello Vue!'
    }
  }
}
</script>

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

全局注册

通过 Vue.component() 方法全局注册组件:

Vue.component('my-component', {
  template: '<div>A custom component!</div>'
})

局部注册

在组件选项中通过 components 属性局部注册:

const ComponentA = { /* ... */ }
const ComponentB = { /* ... */ }

new Vue({
  el: '#app',
  components: {
    'component-a': ComponentA,
    'component-b': ComponentB
  }
})

动态组件

使用 <component> 元素配合 is 特性实现动态组件:

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

<script>
export default {
  data() {
    return {
      currentComponent: 'ComponentA'
    }
  }
}
</script>

函数式组件

无状态、无实例的轻量组件:

Vue.component('functional-button', {
  functional: true,
  render(createElement, context) {
    return createElement('button', context.data, context.children)
  }
})

组件通信

  • Props 向下传递

    <child-component :message="parentMsg"></child-component>
  • Events 向上传递

    <button @click="$emit('enlarge-text')">Enlarge text</button>
  • Provide/Inject

    // 父组件
    provide() {
      return {
        theme: this.theme
      }
    }
    
    // 子组件
    inject: ['theme']

插槽

内容分发机制:

<!-- 父组件 -->
<alert-box>
  Something bad happened.
</alert-box>

<!-- 子组件 -->
<template>
  <div class="alert-box">
    <slot></slot>
  </div>
</template>

组合式 API

Vue 3 的 setup() 函数:

vue实现组件

<script>
import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)
    return { count }
  }
}
</script>

标签: 组件vue
分享给朋友:

相关文章

vue如何实现到期提醒

vue如何实现到期提醒

实现 Vue 到期提醒功能 使用计算属性计算剩余时间 在 Vue 组件中定义一个计算属性,计算目标日期与当前日期的差值。通过 Date 对象获取时间戳并计算剩余天数或小时数。 computed: {…

vue 动画 实现

vue 动画 实现

vue 动画实现方法 Vue 提供了多种方式实现动画效果,主要包括过渡动画和动态动画两类。 使用 <transition> 组件实现基础过渡 通过 Vue 内置的 <transit…

vue实现路由

vue实现路由

Vue 路由的实现方法 Vue 路由可以通过 Vue Router 库来实现,Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue Router 通…

vue实现计算

vue实现计算

Vue 实现计算的方法 在 Vue 中实现计算功能可以通过多种方式完成,主要包括计算属性(computed)、方法(methods)和侦听器(watch)。以下是具体的实现方法: 计算属性(Comp…

vue diff实现

vue diff实现

Vue Diff 算法实现原理 Vue 的虚拟 DOM Diff 算法(即 patch 过程)是其高效渲染的核心,主要通过对比新旧虚拟节点的差异,最小化 DOM 操作。以下是关键实现要点: 同层级比…

vue实现浮标

vue实现浮标

Vue 实现浮动按钮(浮标) 使用 Vue 实现浮动按钮可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 定位和 Vue 组件 创建 Vue 组件并配合 CSS 固定定位实现浮动按钮:…