Vue的属性、方法、生命周期实例代码详解

2020-06-12 21:05:15易采站长站整理

这个生命周期也就是Vue的实例,从开始创建,到创建完成,到挂载,再到更新,然后再销毁的一系列过程,这个官方有一个说法也叫作钩子函数。


<script>
window.onload = () => {
const App = new Vue({
......

// 生命周期第一步:创建前(vue实例还未创建)
beforeCreate() {
// %c 相当于给输出结果定义一个样式
console.log('%cbeforeCreate','color:green', this.$el);
console.log('%cbeforeCreate','color:green', this.message);
},
// 创建完成
created() {
console.log('%ccreated','color:red', this.$el);
console.log('%ccreated','color:red', this.message);
},
// 挂载之前
beforeMount() {
console.log('%cbeforeMount','color:blue', this.$el);
console.log('%cbeforeMount','color:blue', this.message);
},
// 已经挂载但是methods里面的方法还没有执行,从创建到挂载全部完成
mounted() {
console.log('%cmounted','color:orange', this.$el);
console.log('%cmounted','color:orange', this.message);
},
// 创建完之后,数据更新前
beforeUpdate() {
console.log('%cbeforeUpdate','color:#f44586', this.$el);
console.log('%cbeforeUpdate','color:#f44586', this.number);
},
// 数据全部更新完成
updated() {
console.log('%cupdated','color:olive', this.$el);
console.log('%cupdated','color:olive', this.number);
},
// 销毁
beforeDestroy() {
console.log('%cbeforeDestroy','color:gray', this.$el);
console.log('%cbeforeDestroy','color:gray', this.number);
},
destroyed() {
console.log('%cdestroyed','color:yellow', this.$el);
console.log('%cdestroyed','color:yellow', this.number);
}
});
// 打印出来的结果
console.log(App.getSqure);
window.App = App;
};

// 销毁vue实例
function destroy() {
App.$destroy();
}
</script>

html:


<body>
<div id="main">
<span>{{ message }}</span>
<br/>
<span>{{ number }}</span>
<br/>
<button v-on:click="add">add</button>
<br />
<button Onclick="destroy()">destroy</button>
</div>
</body>