vue组件怎么实现功能
创建Vue组件的基本结构
使用Vue单文件组件(SFC)格式,包含<template>、<script>和<style>三个部分。模板部分定义HTML结构,脚本部分处理逻辑,样式部分定义组件外观。
<template>
<div class="my-component">
<!-- 组件内容 -->
</div>
</template>
<script>
export default {
name: 'MyComponent',
// 组件选项
}
</script>
<style scoped>
.my-component {
/* 组件样式 */
}
</style>
定义组件属性(props)
通过props接收父组件传递的数据,可以指定类型和默认值。
props: {
title: {
type: String,
required: true
},
count: {
type: Number,
default: 0
}
}
处理组件内部状态
使用data函数管理组件内部状态,返回一个对象包含所有响应式属性。
data() {
return {
message: 'Hello Vue',
items: []
}
}
添加组件方法
在methods对象中定义组件方法,处理用户交互或业务逻辑。
methods: {
increment() {
this.count++
this.$emit('count-changed', this.count)
},
fetchData() {
// 异步操作
}
}
生命周期钩子使用
利用生命周期钩子在特定阶段执行代码,如created、mounted等。
created() {
console.log('组件已创建')
},
mounted() {
this.fetchData()
}
组件间通信
通过自定义事件($emit)向父组件发送消息,或使用provide/inject跨层级传递数据。
// 子组件触发事件
this.$emit('update', newValue)
// 父组件监听
<child-component @update="handleUpdate" />
使用计算属性和侦听器
计算属性缓存计算结果,侦听器响应数据变化。
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
},
watch: {
count(newVal, oldVal) {
console.log(`count从${oldVal}变为${newVal}`)
}
}
插槽内容分发
使用插槽实现内容分发,支持默认插槽和具名插槽。
<!-- 组件定义 -->
<template>
<div>
<slot name="header"></slot>
<slot></slot>
</div>
</template>
<!-- 组件使用 -->
<my-component>
<template v-slot:header>
<h1>标题</h1>
</template>
<p>主要内容</p>
</my-component>






