{{…">
当前位置:首页 > VUE

vue 组件实现

2026-01-07 20:44:05VUE

Vue 组件实现方法

单文件组件 (SFC)

使用 .vue 文件格式,包含模板、脚本和样式三部分:

<template>
  <div class="example">{{ msg }}</div>
</template>

<script>
export default {
  data() {
    return {
      msg: 'Hello World!'
    }
  }
}
</script>

<style scoped>
.example {
  color: red;
}
</style>

选项式 API

通过对象属性定义组件行为:

export default {
  props: ['title'],
  data() {
    return { count: 0 }
  },
  methods: {
    increment() {
      this.count++
    }
  }
}

组合式 API

使用 setup 函数组织逻辑:

vue 组件实现

import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)
    function increment() {
      count.value++
    }
    return { count, increment }
  }
}

全局注册

在应用入口文件全局注册组件:

import { createApp } from 'vue'
import MyComponent from './MyComponent.vue'

const app = createApp({})
app.component('MyComponent', MyComponent)

局部注册

在父组件中局部注册:

vue 组件实现

import ChildComponent from './ChildComponent.vue'

export default {
  components: {
    ChildComponent
  }
}

动态组件

使用 <component :is> 实现动态渲染:

<template>
  <component :is="currentComponent" />
</template>

异步组件

通过 defineAsyncComponent 实现懒加载:

import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent(() =>
  import('./components/AsyncComponent.vue')
)

组件通信

  • Props 传数据:<Child :propName="value" />
  • 事件发射:this.$emit('eventName', payload)
  • Provide/Inject:跨层级传递
  • Vuex/Pinia:状态管理

生命周期钩子

export default {
  created() {
    console.log('组件创建完成')
  },
  mounted() {
    console.log('DOM挂载完成')
  }
}

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

相关文章

vue实现下拉菜单

vue实现下拉菜单

实现下拉菜单的基本思路 使用Vue实现下拉菜单可以通过动态绑定v-show或v-if控制菜单显示隐藏,结合事件监听(如@click或@mouseenter)触发状态切换。以下是两种常见实现方式:…

vue实现图片搜索

vue实现图片搜索

Vue实现图片搜索功能 使用HTML5的File API获取图片 通过<input type="file">元素让用户选择图片文件,使用FileReader对象读取图片数据。 <…

vue循环数组实现

vue循环数组实现

vue循环数组的实现方法 在Vue中循环数组主要通过v-for指令实现,以下是几种常见用法: 基本数组循环 使用v-for指令遍历数组,可以通过(item, index)的语法获取当前项和索引值:…

vue 页签实现

vue 页签实现

Vue 页签实现方法 在 Vue 中实现页签功能通常涉及动态组件、路由或状态管理。以下是几种常见的实现方式: 使用动态组件 通过 Vue 的 <component> 动态组件结合 v-f…

vue搜索过后实现分页

vue搜索过后实现分页

Vue 实现搜索后分页功能 数据绑定与搜索逻辑 在 Vue 组件中定义必要的数据属性: data() { return { searchQuery: '', currentPag…

vue单页面实现登录

vue单页面实现登录

实现登录功能的基本流程 在Vue单页面应用中实现登录功能,通常需要以下几个关键步骤: 创建登录表单组件 使用Vue的模板语法创建包含用户名和密码输入框的表单,并绑定数据到组件的data属性。 <…