Vue.js组件开发

Vue.js 组件开发分步教程

一、组件创建基础
  1. 全局注册组件 通过 Vue.component() 方法注册全局组件,可在所有 Vue 实例中使用1
  2. Vue.component('global-button', {
      template: '<button @click="count++">点击次数:{{ count }}</button>',
      data() {
        return { count: 0 }
      }
    })
  3. 局部注册组件 在父组件内通过 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>
三、组件间通信
  1. Props 父传子 父组件通过属性传递数据,子组件用 props 接收4
    <!-- 父组件 -->
    <child-component :items="dataList" title="用户列表"/>
  1. 自定义事件子传父 子组件通过 $emit 触发事件:
    // 子组件
    this.$emit('update-data', newData)
    
    // 父组件
    <child-component @update-data="handleUpdate"/>
  2. 非父子组件通信 可通过 Event Bus 或 Vuex 实现:
    // 创建事件总线
    const bus = new Vue()
    
    // 组件A发送事件
    bus.$emit('global-event', payload)
    
    // 组件B监听事件
    bus.$on('global-event', callback)
    四、生命周期应用示例

    利用 mountedbeforeDestroy 实现数据初始化与清理4

    export default {
      data() { return { timer: null } },
      mounted() {
        this.timer = setInterval(() => {
          console.log('组件已挂载')
        }, 1000)
      },
      beforeDestroy() {
        clearInterval(this.timer)
      }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值