Vue组件使用/单个组件的生命周期

- props 和 $emit
 props: 用于父组件传递data数据给子组件,比如在index.vue中,data函数里面有个list数据,把它传给List组件(下图1),在List组件内用list属性来接收(下图2)
  
  
$emit:事件触发,在index.vue中在两个子组件内传入了两个方法:add delete。


这俩方法作为 父组件给子组件的 两个事件。
在Input组件中,通过点击事件:

点击事件来触发this.$emit('add'),这里的add和父组件传给子组件的方法@add一样。

同理,在List组件中的delete删除事件也是一样。在子组件List中点击按钮,就会执行删除事件。


父到子,传递数据;子到父,触发事件。
- ❗自定义事件(兄弟组件通信)
 import event from './event'
  
要实现Input.vue和List.vue之间通信:在input输入内容之后点击add按钮会在控制台打印出'on add title'。打印的方法在List.vue中👇

且在List.vue中自定义事件👇

这个自定义事件在Input.vue触发👇

注意一个重要的点:👇 在beforeDestroy中要及时解绑自定义事件,否则可能造成内存泄漏。

在一个组件绑定一个事件,在另一个组件中触发这个事件。
- 组件的生命周期
 挂载(beforeCreate、created、beforeMount、Mounted)、更新(beforeUpdate、Updated)、销毁(beforeDestroy、Destroyed)
  
 创建是从外到内的,渲染是从内到外的。 
Parent beforeCreate
Parent created
Parent beforeMount
  Child beforeCreate
  Child created
  Child beforeMount
  Child mounted
Parent mounted
初始化时,一定要父组件先初始化,子组件才能初始化。但是渲染的时候子组件要先渲染完再渲染父组件。
更新:先后问题

Parent beforeUpdate
  Child beforeUpdate
  Child updated
Parent updated
销毁:先后问题
先销毁子组件,再销毁父组件。 Vue3👇
Parent beforeUnmount
  Child beforeUnmount
  Child unmounted
Parent unmounted
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号