当前位置:首页 > 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 示例:

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

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

vue基础组件实现

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

相关文章

vue轮播组件实现

vue轮播组件实现

Vue 轮播组件实现方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template&g…

vue轮播组件实现

vue轮播组件实现

vue轮播组件实现方法 使用第三方库(如Swiper) 安装Swiper库: npm install swiper 在Vue组件中引入: <template> <div…

vue实现折叠组件

vue实现折叠组件

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

如何缓存react组件

如何缓存react组件

缓存React组件的方法 React.memo 使用React.memo对函数组件进行浅比较缓存,避免不必要的重新渲染。适用于props不变的场景。 const MemoizedComponen…

如何学java基础

如何学java基础

学习Java基础的方法 理解Java的基本概念 Java是一种面向对象的编程语言,掌握基础概念如类、对象、继承、多态和封装是必要的。熟悉Java的语法结构,包括变量、数据类型、运算符和控制语句。…

vue实现组件切换

vue实现组件切换

Vue 组件切换的实现方法 在 Vue 中实现组件切换有多种方式,以下是几种常见的方法: 动态组件 使用 Vue 内置的 <component> 元素和 is 属性可以动态切换组件:…