当前位置:首页 > VUE

vue基础组件实现

2026-02-18 20:58:30VUE

Vue 基础组件实现

组件定义

在 Vue 中,组件是可复用的 Vue 实例,通常以 .vue 文件形式组织,包含模板、脚本和样式三部分。一个基础组件的结构如下:

<template>
  <div class="my-component">
    {{ message }}
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {
    message: {
      type: String,
      default: 'Hello Vue!'
    }
  }
}
</script>

<style scoped>
.my-component {
  color: blue;
}
</style>

组件注册

组件需注册后才能使用。全局注册通过 Vue.component 实现,局部注册在父组件的 components 选项中完成。

全局注册示例(在入口文件如 main.js 中):

import Vue from 'vue';
import MyComponent from './MyComponent.vue';

Vue.component('MyComponent', MyComponent);

局部注册示例(在父组件中):

<script>
import MyComponent from './MyComponent.vue';

export default {
  components: {
    MyComponent
  }
}
</script>

Props 数据传递

父组件通过 props 向子组件传递数据。子组件需在 props 选项中声明接收的属性。

父组件调用:

<template>
  <my-component message="Custom Message" />
</template>

事件通信

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

子组件触发事件:

<script>
export default {
  methods: {
    handleClick() {
      this.$emit('custom-event', 'event-data');
    }
  }
}
</script>

父组件监听:

<template>
  <my-component @custom-event="handleEvent" />
</template>

<script>
export default {
  methods: {
    handleEvent(data) {
      console.log(data); // 输出 'event-data'
    }
  }
}
</script>

插槽内容分发

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

子组件定义插槽:

<template>
  <div>
    <slot name="header"></slot>
    <slot>默认内容</slot>
  </div>
</template>

父组件使用插槽:

<template>
  <my-component>
    <template v-slot:header>
      <h1>标题</h1>
    </template>
    <p>主要内容</p>
  </my-component>
</template>

生命周期钩子

常用生命周期钩子包括 createdmountedupdateddestroyed,用于在组件不同阶段执行逻辑。

示例:

<script>
export default {
  created() {
    console.log('组件实例已创建');
  },
  mounted() {
    console.log('DOM 挂载完成');
  }
}
</script>

状态管理

对于跨组件状态共享,小型项目可用 provide/inject,中大型项目推荐 Vuex。

provide/inject 示例:

vue基础组件实现

<script>
// 祖先组件
export default {
  provide() {
    return {
      sharedData: '共享数据'
    };
  }
}
</script>

<script>
// 后代组件
export default {
  inject: ['sharedData'],
  created() {
    console.log(this.sharedData); // 输出 '共享数据'
  }
}
</script>

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

相关文章

vue组件传值实现分页

vue组件传值实现分页

Vue组件传值实现分页的方法 在Vue中实现分页功能,通常需要父子组件之间的数据传递。以下是几种常见的传值方式: 使用props传递数据 父组件通过props向子组件传递当前页码和总页数等分页信息:…

uniapp 滑动组件

uniapp 滑动组件

uniapp 滑动组件实现方法 使用swiper组件 uniapp内置的swiper组件可以实现滑动效果,适用于轮播图或页面切换场景。 示例代码: <swiper :indicator-d…

vue 实现table组件

vue 实现table组件

Vue 实现 Table 组件 基础表格结构 使用 Vue 的模板语法构建表格的基本框架,通过 v-for 动态渲染数据。 <template> <table>…

vue实现布局组件

vue实现布局组件

Vue 实现布局组件的方法 基础布局组件结构 使用 Vue 的单文件组件(SFC)创建一个基础布局组件。布局组件通常包含头部、侧边栏、主体内容和页脚。 <template> <…

vue组件化实现

vue组件化实现

Vue 组件化实现 Vue 的组件化是将 UI 拆分为独立、可复用的模块,每个模块封装自己的逻辑和样式。以下是实现 Vue 组件化的核心方法: 组件定义 使用 .vue 单文件组件(SFC)是最常见…

vue实现组件跳转

vue实现组件跳转

vue实现组件跳转的方法 在Vue中实现组件跳转有多种方式,以下是常见的几种方法: 使用<router-link>进行导航 <router-link to="/path/to/c…