Vue.js 组件开发分步教程
一、组件创建基础
- 全局注册组件 通过
Vue.component()
方法注册全局组件,可在所有 Vue 实例中使用1: -
Vue.component('global-button', { template: '<button @click="count++">点击次数:{{ count }}</button>', data() { return { count: 0 } } })
- 局部注册组件 在父组件内通过
components
选项注册,仅限当前组件作用域4:
const LocalCounter = {
template: '<div>当前值:{{ num }} <button @click="num++">+</button></div>',
data() { return { num: 0 } }
}
new Vue({
el: '#app',
components: { 'local-counter': LocalCounter }
})
二、组件标准结构
采用单文件组件(.vue)形式,包含三个核心部分2:
<template>
<div class="user-card">
<img :src="avatar" class="avatar">
<h3>{{ username }}</h3>
<p v-if="bio">{{ bio }}</p>
</div>
</template>
<script>
export default {
name: 'UserCard',
props: {
username: { type: String, required: true },
avatar: String,
bio: String
}
}
</script>
<style scoped>
.user-card {
border: 1px solid #eaeaea;
padding: 20px;
}
.avatar {
width: 80px;
height: 80px;
border-radius: 50%;
}
</style>
三、组件间通信
- Props 父传子 父组件通过属性传递数据,子组件用
props
接收4:<!-- 父组件 --> <child-component :items="dataList" title="用户列表"/>
- 自定义事件子传父 子组件通过
$emit
触发事件:// 子组件 this.$emit('update-data', newData) // 父组件 <child-component @update-data="handleUpdate"/>
- 非父子组件通信 可通过 Event Bus 或 Vuex 实现:
// 创建事件总线 const bus = new Vue() // 组件A发送事件 bus.$emit('global-event', payload) // 组件B监听事件 bus.$on('global-event', callback)
四、生命周期应用示例
利用
mounted
和beforeDestroy
实现数据初始化与清理4:export default { data() { return { timer: null } }, mounted() { this.timer = setInterval(() => { console.log('组件已挂载') }, 1000) }, beforeDestroy() { clearInterval(this.timer) } }