beforecreate
此时组件的选项对象还未创建,el 和 data 并未初始化,因此无法访问methods, data, computed等上的方法和数据。
<template>
<div>
<p>{{msg}}</p>
<button @click="change">改变</button>
</div>
</template>
<script>
export default {
data(){
return{
msg:'hello vue'
}
},
beforeCreate(){
console.log(this.msg);
console.log(this.change)
},
methods:{
change(){
this.msg='hello'
console.log('已经改变了')
}
}
}
</script>
<style>
</style>
created
实例已经创建完成之后被调用。在这一步,实例已完成以下配置:数据观测、属性和方法的运算,watch/event事件回调,完成了data 数据的初始化,el没有。
此时会编译模板,将data里的数据和template模板,生成HTML
<template>
<div>
<p>{{msg}}</p>
<button @click="change">改变</button>
</div>
</template>
<script>
export default {
data(){
return{
msg:'hello vue'
}
},
created(){
console.log(this.msg);
console.log(this.change)
},
methods:{
change(){
this.msg='hello'
console.log('已经改变了')
}
}
}
</script>
<style>
</style>
beforemount
此时还没有生成HTML到页面上
mounted
挂载完成,将模板中的html渲染到页面上,此时可以监控data,更新dom
此时可以做ajax
mounted只会执行一次
<template>
<div>
<p>{{msg}}</p>
<button @click="change">改变</button>
</div>
</template>
<script>
export default {
data(){
return{
msg:'hello vue'
}
},
mounted(){
this.msg='你好'
this.change()
console.log(this.msg);
console.log(this.change)
},
methods:{
change(){
console.log('已经改变了')
}
}
}
</script>
<style>
</style>