当前位置:首页 > 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 的递归组件特性可以轻松实现无限级嵌套菜单。通过组件调用自身的方式处理嵌套数据。 <template> <ul&…

vue 实现

vue 实现

Vue 实现的基本步骤 安装 Vue.js 可以通过 npm 或 CDN 引入。使用 npm 安装适合大型项目,CDN 适合快速原型开发。 npm install vue 在 HTML 文件中引入…

vue实现visual

vue实现visual

Vue 实现可视化(Visual)的常见方法 在 Vue 中实现可视化通常涉及数据可视化库的集成,以下是几种主流方案: 使用 ECharts ECharts 是一个强大的 JavaScript 图表…

vue如何实现登录

vue如何实现登录

实现登录功能的基本步骤 使用Vue实现登录功能通常需要结合后端API、状态管理以及路由控制。以下是常见的实现方式: 创建登录表单组件 在Vue组件中构建包含用户名和密码输入框的表单: <te…

vue实现匹配显示

vue实现匹配显示

Vue实现匹配显示的方法 使用v-if或v-show指令 通过条件渲染指令v-if或v-show,可以根据条件匹配显示不同的内容。v-if会完全销毁或重建DOM元素,而v-show仅切换CSS的dis…

vue实现弹层

vue实现弹层

Vue 实现弹层的方法 使用 Vue 原生组件实现弹层 创建一个基础的弹层组件,利用 v-if 或 v-show 控制显示隐藏。 <template> <div class="…