您的位置:首页 > Web前端 > Vue.js

Vue父子组件声明周期

2018-09-21 11:31 197 查看

 记录下,避免忘了,还要做

 

[code]<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue</title>
<script src="./vue/vue.js"></script>
<script src="./vue/vue-router.min.js"></script>
<style>
</style>
</head>
<body>
<div id="app">
<span @click="childmsg = 'childnewsmsg'">{{ msg }}</span>
<cpt-child :msg="childmsg"></cpt-child>
</div>
</body>
<script>
var child = Vue.extend({
template: '<div>cpt-child:{{ msg }}</div>',
props: {
msg: String
},
beforeCreate: function(){
console.log('beforecreate parent')
},
created: function(){
console.log('created parent')
},
beforeMount: function(){
console.log('beforeMount parent')
},
mounted: function(){
console.log('mounted parent')
},
beforeUpdate: function(){
console.log('beforeUpdate parent')
},
updated: function(){
console.log('updated parent')
},
beforeDestroy: function(){
console.log('beforeDestroy parent')
},
destroyed: function(){
console.log('destroyed parent')
}
})
var vm = new Vue({
el: '#app',
data: {
msg: 'msg',
childmsg: 'childmsg'
},
watch: {
childmsg: function(newVal,oldVal){
console.log('watch change')
}
},
components: {
'cpt-child': child
},
beforeCreate: function(){
console.log('beforecreate child')
},
created: function(){
console.log('created child')
},
beforeMount: function(){
console.log('beforeMount child')
},
mounted: function(){
console.log('mounted child')
},
beforeUpdate: function(){
console.log('beforeUpdate child')
},
updated: function(){
console.log('updated child')
},
beforeDestroy: function(){
console.log('beforeDestroy child')
},
destroyed: function(){
console.log('destroyed child')
}
})
</script>
</html>

 这是按照渲染顺序console的结果,然后点击span后显示的结果。

结论:

先初始化父组件的数据,在初始化子组件的数据。

加载是相反的,先加载父组件,在加载子组件。

watch优先于update。

beforeUpdate是子组件优先,update是父组件优先。

总而言之,处理数据是子组件优先,加载到dom是父组件优先。

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: