当前位置:首页 > VUE

vue中组件实现

2026-01-19 21:47:04VUE

Vue 组件实现方法

全局注册组件

通过 Vue.component() 方法全局注册组件,在任何 Vue 实例中均可使用。注册时需指定组件名称和配置对象:

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

局部注册组件

在 Vue 实例或组件的 components 选项中局部注册,仅当前作用域可用:

const MyComponent = {
  template: '<div>局部组件内容</div>'
};

new Vue({
  el: '#app',
  components: { 'my-component': MyComponent }
});

单文件组件(SFC)

使用 .vue 文件组织组件,包含模板、逻辑和样式:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return { message: '单文件组件示例' };
  }
};
</script>

<style scoped>
div { color: red; }
</style>

动态组件

通过 <component :is="currentComponent"> 实现动态切换组件,需配合 keep-alive 缓存状态:

<keep-alive>
  <component :is="currentTabComponent"></component>
</keep-alive>

异步组件

使用 import() 语法实现按需加载,提升应用性能:

Vue.component('async-component', () => import('./AsyncComponent.vue'));

组件通信

  • Props 向下传递:父组件通过属性传递数据
    <child-component :prop-name="parentData"></child-component>
  • $emit 向上通知:子组件触发事件
    this.$emit('event-name', payload);
  • Provide/Inject:跨层级数据传递
    provide() { return { theme: this.theme } },
    inject: ['theme']

插槽(Slots)

  • 默认插槽:
    <slot>后备内容</slot>
  • 具名插槽:
    <slot name="header"></slot>
  • 作用域插槽:
    <slot :item="item"></slot>

渲染函数

通过 render 函数直接生成虚拟 DOM,适用于复杂动态场景:

vue中组件实现

render(h) {
  return h('div', this.$slots.default);
}

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

相关文章

vue实现按钮刷新

vue实现按钮刷新

Vue 实现按钮刷新功能 在 Vue 中实现按钮刷新功能可以通过多种方式实现,具体取决于刷新需求是局部刷新还是全局刷新。以下是几种常见的方法: 使用 window.location.reload()…

vue 实现jqslidedown

vue 实现jqslidedown

在 Vue 中实现类似 jQuery 的 slideDown 效果,可以通过 Vue 的过渡系统或 CSS 动画结合动态样式绑定来实现。以下是几种实现方式: 使用 Vue Transition 组件…

vue 分页 实现

vue 分页 实现

Vue 分页实现方法 使用第三方库(如 Element UI) Element UI 提供了现成的分页组件 el-pagination,适合快速集成。 安装 Element UI: npm ins…

vue实现tip

vue实现tip

Vue实现Tooltip的方法 使用Vue实现Tooltip可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML的title属性 在Vue模板中直接使用HTML的title属性是最简单的实…

vue歌词滚动实现

vue歌词滚动实现

实现 Vue 歌词滚动的核心方法 监听当前播放时间 通过 audio 元素的 timeupdate 事件获取当前播放时间,并与歌词时间戳对比。在 Vue 中使用 @timeupdate 绑定事件:…

vue实现特效轮播

vue实现特效轮播

Vue实现特效轮播的方法 使用Vue实现轮播效果可以通过多种方式完成,以下是几种常见的实现方法。 使用Vue和CSS动画 通过Vue的动态绑定和CSS动画结合,可以实现平滑的轮播效果。 &…