当前位置:首页 > 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,适用于复杂动态场景:

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

vue中组件实现

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

相关文章

vue实现多个tab

vue实现多个tab

Vue 实现多个 Tab 的方法 使用动态组件切换 在 Vue 中可以通过动态组件 <component :is="currentTab"> 结合 v-for 和 v-bind 实现多个…

vue实现微博发布动态

vue实现微博发布动态

使用Vue实现微博发布动态功能 创建Vue组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="w…

vue实现密码框的包

vue实现密码框的包

Vue 密码框实现方案 在 Vue 中实现密码框功能,可以通过原生 HTML 结合 Vue 指令或使用第三方组件库完成。以下是几种常见方案: 原生 HTML + Vue 双向绑定 <t…

vue实现一个标签选择

vue实现一个标签选择

Vue 标签选择组件实现 基础实现 使用 Vue 的 v-for 和 v-model 指令可以快速实现标签选择功能: <template> <div class="tag-s…

vue实现store

vue实现store

Vue 实现 Store 在 Vue 中,可以通过 Vuex 或 Pinia 实现全局状态管理(Store)。以下是两种主流方案的实现方法。 使用 Vuex 实现 Store Vuex 是 Vue…

vue 实现toast

vue 实现toast

vue 实现 toast 的方法 在 Vue 中实现 Toast 提示功能可以通过多种方式,以下是几种常见的实现方法: 使用第三方库 Vue 生态中有许多成熟的 Toast 库,例如 vue-toa…