当前位置:首页 > VUE

vue中组件实现

2026-01-19 21:47:04VUE

Vue 组件实现方法

全局注册组件

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

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

局部注册组件

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

vue中组件实现

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 缓存状态:

vue中组件实现

<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实现单词反转

实现思路 在Vue中实现单词反转功能,可以通过多种方式完成。核心思路是利用JavaScript的字符串处理方法,将输入的单词或句子拆分为数组,反转数组后再拼接成字符串。 方法一:使用计算属性 通过…

vue点击实现排序

vue点击实现排序

实现点击排序的方法 在Vue中实现点击排序功能,可以通过以下几种方式完成: 使用计算属性结合排序方法 定义一个响应式数据存储排序状态,通过计算属性动态返回排序后的数组。点击事件切换排序状态。…

vue实现查询替换

vue实现查询替换

Vue 实现查询替换功能 在 Vue 中实现查询替换功能,可以通过数据绑定和字符串操作方法结合实现。以下是具体实现方式: 基础实现 <template> <div>…

vue实现按卡片轮播

vue实现按卡片轮播

实现卡片轮播的基本思路 在Vue中实现卡片轮播可以通过结合v-for指令和动态样式绑定完成。核心是维护一个当前显示卡片的索引,通过CSS过渡效果实现平滑切换。 基础实现步骤 模板部分 使用v-for…

vue 实现在线预览

vue 实现在线预览

Vue 实现在线预览的常见方法 使用 iframe 嵌入 通过 iframe 标签可以嵌入多种类型的文件,如 PDF、图片、网页等。需要确保文件地址可访问。 <template>…

vue实现多用户登录

vue实现多用户登录

实现多用户登录的基本思路 在Vue中实现多用户登录通常需要结合后端API完成身份验证,并通过前端路由、状态管理(如Vuex或Pinia)和本地存储(如localStorage)来管理用户会话。以下是关…