当前位置:首页 > VUE

vue基础组件实现

2026-01-18 04:32:22VUE

Vue 基础组件实现

组件定义

使用 Vue.component 全局注册或局部注册组件。全局注册适合通用组件,局部注册适合特定页面使用的组件。

// 全局注册
Vue.component('my-component', {
  template: '<div>基础组件内容</div>'
});

// 局部注册
const MyComponent = {
  template: '<div>局部组件内容</div>'
};
new Vue({
  el: '#app',
  components: { MyComponent }
});

模板语法

组件模板支持 HTML 和 Vue 指令(如 v-ifv-for)。单文件组件(.vue 文件)需配合构建工具使用。

<template>
  <div>
    <p v-if="showText">{{ message }}</p>
    <button @click="toggleText">切换显示</button>
  </div>
</template>

Props 数据传递

父组件通过 props 向子组件传递数据。使用 v-bind 动态传递或直接传递静态值。

vue基础组件实现

// 子组件定义
Vue.component('child-component', {
  props: ['title'],
  template: '<h3>{{ title }}</h3>'
});

// 父组件使用
<child-component title="动态标题" :dynamic-title="parentData"></child-component>

事件通信

子组件通过 $emit 触发事件,父组件通过 v-on 监听。

// 子组件触发事件
this.$emit('custom-event', eventData);

// 父组件监听
<child-component @custom-event="handleEvent"></child-component>

插槽内容分发

使用 <slot> 实现内容分发,支持默认插槽和命名插槽。

vue基础组件实现

<!-- 子组件 -->
<div>
  <slot name="header"></slot>
  <slot>默认内容</slot>
</div>

<!-- 父组件 -->
<child-component>
  <template v-slot:header><h1>标题</h1></template>
  <p>主内容</p>
</child-component>

生命周期钩子

在组件不同阶段执行逻辑,如 createdmounted

Vue.component('lifecycle-demo', {
  created() {
    console.log('组件实例创建完成');
  },
  mounted() {
    console.log('DOM 挂载完成');
  }
});

样式与作用域

单文件组件中可通过 <style scoped> 限制样式作用域。

<style scoped>
.button {
  color: red; /* 仅作用于当前组件 */
}
</style>

动态组件

使用 <component :is="currentComponent"> 实现动态切换组件。

<component :is="tabComponent"></component>

注意事项

  • 组件命名建议使用 kebab-case(如 my-component)。
  • 避免直接修改 props,如需修改应使用本地 data 或计算属性。
  • 复杂状态管理建议配合 Vuex 使用。

标签: 组件基础
分享给朋友:

相关文章

vue组件的实现

vue组件的实现

Vue 组件的实现方式 Vue 组件可以通过多种方式实现,主要包括单文件组件(SFC)、全局注册和局部注册。以下是常见的实现方法: 单文件组件(SFC) 单文件组件是 Vue 最推荐的组件化开发方…

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

实现拖拽组件嵌套的核心思路 Vue中实现拖拽组件嵌套需要结合拖拽库(如vuedraggable)和组件递归渲染。核心在于动态管理嵌套数据结构,并通过事件传递实现层级更新。 安装必要依赖 推荐使用vu…

vue实现折叠组件

vue实现折叠组件

实现折叠组件的基本思路 在Vue中实现折叠组件通常需要利用动态绑定和条件渲染。核心是通过控制一个布尔值状态来决定内容是否显示,并添加过渡动画提升用户体验。 基础实现方法 使用v-show或v-if控…

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性来完成。以下是几种常见的实…

vue实现tooltips组件

vue实现tooltips组件

实现基础 Tooltip 组件 创建一个名为 Tooltip.vue 的单文件组件,包含模板、样式和逻辑: <template> <div class="tooltip-con…

vue 实现组件刷新

vue 实现组件刷新

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