{…">
当前位置:首页 > 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 函数组织逻辑:

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)

局部注册

在父组件中局部注册:

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菜单实现

Vue 菜单实现方法 使用 Element UI 的菜单组件 Element UI 提供了现成的菜单组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用 el-menu 相关组件。…

vue实现公式

vue实现公式

在Vue中实现公式展示或计算可以通过多种方式实现,以下为具体方法: 使用模板插值与计算属性 若公式较简单,可直接在模板中使用插值表达式或计算属性。例如计算圆的面积: <templat…

vue实现switch

vue实现switch

Vue 实现 Switch 开关组件 在 Vue 中实现 Switch 开关组件可以通过自定义组件或使用现有 UI 库完成。以下是几种常见实现方式: 自定义 Switch 组件 创建一个基础 Sw…

vue实现返回

vue实现返回

返回按钮功能实现 在Vue中实现返回功能通常有两种方式:使用浏览器历史记录的history.back()或结合Vue Router进行编程式导航。以下是具体实现方法: 使用浏览器API met…

vue alert实现

vue alert实现

使用 Vue 实现 Alert 组件 在 Vue 中实现 Alert 组件可以通过自定义组件或结合第三方库完成。以下是几种常见方法: 自定义 Alert 组件 创建一个可复用的 Alert 组件,…

vue实现骰子

vue实现骰子

Vue 实现骰子功能 创建 Vue 组件 在 Vue 项目中创建一个骰子组件,例如 Dice.vue。该组件包含骰子的外观和逻辑。 <template> <div class=…