父向子传值
//父组件中内容 app.vue
<MyList/ :list="list">
data(){
list:[]
}
//子组件中 list.vue
<li v-for="item in list" :key="item.id"></li>
props:{
lsit: Array
}
子向父
子组件内容
<input type="text" v-model="title">
<button @click="add">添加</button>
data(){
title:''
}
methods:{
add(){
this.$emit('add',this.title) //在父组件中触发add事件,将值带出去
}
}
父组件内容
<MyInput @add="add" />
methods:{
add(title){
this.list.push({
id:3,
title:title //简写成title也可以
})
}
}
兄弟组件通信:将input中的内容在list中输出
中间件event-bus.vue
import Vue from 'vue'
const eventBus = new Vue()
export default eventBus
兄弟组件 input.vue
import eventBus from './event-bus'
methods:{
add(){
eventBus.$emit('addItem',this.title)
}
}
兄弟组件 list.vue
import eventBus from './event-bus'
methods:{
handleAddTitle(title){
console.log(title) //输出从兄弟组件中传过来的值
}
}
mounted(){ //组件挂载的时候 真实dom渲染
eventBus.$on('addItem',this.handleAddTitle)
}
beforDestroy()
eventBus.$off('addItem',this.handleAddTitle) //组件销毁的时候 解绑事件,
//避免潜在的内存泄漏的问题
}
父子组件生命周期执行顺序
父:created()
子:created()
子:mounted()
父:mounted()
更新
父:beforeUpdate()
子:beforeUpdate()
子:updated()
父:updated()
销毁
父:beforeDestory()
子:beforeDestory()
子:Destory()
父:Destory()