学习进度条

每日总结(带代码示例)

今日学习时间:1小时
今日代码量:100行
今日博客:1篇(Vue 组件通信方式总结


1. Props 和 $emit(父子组件通信)

<!-- 父组件 Parent.vue -->
<template>
  <Child :message="parentMsg" @update="handleUpdate" />
</template>

<script>
export default {
  data() {
    return {
      parentMsg: "Hello from Parent"
    }
  },
  methods: {
    handleUpdate(newMsg) {
      this.parentMsg = newMsg
    }
  }
}
</script>

<!-- 子组件 Child.vue -->
<template>
  <div>
    <p>收到父组件消息:{{ message }}</p>
    <button @click="sendToParent">回复父组件</button>
  </div>
</template>

<script>
export default {
  props: ['message'],
  methods: {
    sendToParent() {
      this.$emit('update', 'Hello from Child')
    }
  }
}
</script>

2. v-model 与 .sync(双向绑定)

<!-- 自定义输入组件 MyInput.vue -->
<template>
  <input 
    :value="value" 
    @input="$emit('update:value', $event.target.value)"
  />
</template>

<script>
export default {
  props: ['value']
}
</script>

<!-- 使用方式 -->
<template>
  <!-- Vue 2的.sync用法 -->
  <MyInput :value.sync="inputValue" />
  
  <!-- Vue 3统一使用v-model -->
  <MyInput v-model="inputValue" />
</template>

3. $refs 获取组件实例

<template>
  <ChildComponent ref="child" />
  <button @click="callChildMethod">调用子组件方法</button>
</template>

<script>
export default {
  methods: {
    callChildMethod() {
      this.$refs.child.doSomething()
      // 也可以访问DOM元素
      // this.$refs.someInput.focus()
    }
  }
}
</script>

4. Event Bus(事件总线)

// eventBus.js
import Vue from 'vue'
export default new Vue()

// 组件A(发送事件)
import eventBus from './eventBus'
export default {
  methods: {
    sendMessage() {
      eventBus.$emit('global-event', 'Some data')
    }
  }
}

// 组件B(接收事件)
export default {
  created() {
    eventBus.$on('global-event', data => {
      console.log('收到数据:', data)
    })
  },
  beforeDestroy() {
    // 记得移除监听
    eventBus.$off('global-event')
  }
}

5. Provide / Inject(跨级组件通信)

<!-- 祖先组件 -->
<script>
export default {
  provide() {
    return {
      theme: 'dark',
      toggleTheme: this.toggleTheme
    }
  },
  methods: {
    toggleTheme() {
      this.theme = this.theme === 'dark' ? 'light' : 'dark'
    }
  }
}
</script>

<!-- 后代组件(任意层级) -->
<script>
export default {
  inject: ['theme', 'toggleTheme'],
  methods: {
    handleClick() {
      this.toggleTheme()
      console.log('当前主题:', this.theme)
    }
  }
}
</script>

今日实践重点

  1. 用事件总线实现了跨组件通知功能
  2. 通过provide/inject实现了主题切换功能
  3. 对比了v-model和.sync的异同

遇到的问题

  • 事件总线需要手动清除监听(解决方案:在beforeDestroy钩子中调用$off)
  • provide的响应式数据需要特殊处理(Vue 2可用observable,Vue 3直接用ref)
posted @ 2025-04-13 15:21  haoyinuo  阅读(5)  评论(0)    收藏  举报