1 - Vue 生命周期
vue 有: created、mounted、updated、destroyed 每个生命周期前面都有beforeXxx()
- 创建实例前后,beforeCreate(), created()
- mounted 前后,beforeMount(), mounted() (异步请求在mounted调用)
- 数据变化 前后,beforeUpdate(), updated()
- 结束 前后,beforeDestroy(), destroyed()
<template>
<div id="hello">
<h1>{{ msg }}</h1>
<input v-model="input" placeholder="edit me">
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App',
input: '123'
}
},
beforeCreate () {
console.log('beforeCreate', this)
console.log(this.$el) // undefined
console.log(this.$data) // undefined
console.log(this.input) // undefined
},
created () {
console.log('created')
console.log(this.$el) // undefined
console.log(this.$data) // {__ob__: Observer} { input: "123" msg: "Welcome to Your Vue.js App" }
console.log(this.input) // 123
},
beforeMount () {
// render 之前
console.log('beforeMount')
console.log(this.$el) // undefined
console.log(this.$data) // {__ob__: Observer} { input: "123" msg: "Welcome to Your Vue.js App" }
console.log(this.input) // 123
},
mounted () {
// 替换<div id="app"></div>后
console.log('mounted')
console.log(this.$el) // <div id="hello"><h1>Welcome to Your Vue.js App</h1> <input placeholder="edit me"></div>
console.log(this.$data) // {__ob__: Observer} { input: "123" msg: "Welcome to Your Vue.js App" }
console.log(this.input) // 123
this.msg = 'title 测试'
},
beforeUpdate () {
// 数据更新时调用,发生在虚拟 DOM 重新渲染和打补丁之前
console.log('beforeUpdate') // this.msg = 'title 测试' 因为数据变化了, 所有触发了该流程
// 此时还是 <div id="hello"><h1>Welcome to Your Vue.js App</h1> <input placeholder="edit me"></div>
},
updated () {
console.log('updated')
// <div id="hello"><h1>title 测试</h1> <input placeholder="edit me"></div>
},
// 实例销毁之前调用
beforeDestroy () { console.log('beforeDestroy') },
// 实例销毁
destroyed () { console.log('destroyed') }
}
</script>
2 - 组件通信
LIN.JY666:[React] 7 - 组件通信
常见的几种模式:
- 父组件 => 子组件 props
- 子组件 => 父组件 $emit / v-on / 回调
- eventBus 类似 React用法 new EventEmitter() 订阅发布模式
- Vuex 全局管理
3 - computed vs watch?
- computed: 计算某个值,并该值依赖其他数据。
- watch: 值变化前后的观测。