
从destroyed的字面意思可知,中文意为是“销毁”的意思,当我们离开这个页面的时候,便会调用这个函数(具体可以看看vue的的生命周期),我们常用来销毁一些监听事件及定时函数,例如:
// 销毁监听事件
destroyed() {
window.removeEventListener('resize', this.resizeWin)
}从上函数可知,当用户离开页面的时候便会销毁监听事件。

vue中生命周期分为初始化,跟新状态,销毁三个阶段
1、初始化阶段:beforeCreated,created,beforeMount,mounted
beforeCreate():在beforeCreate()生命周期函数执行的时候,vue对象中的data和methods中的数据没有初始化,在beforeCreate()中无法访问data数据和methods中的方法;
created():此时data数据和methods中的方法已经初始化好了,也就是说,created()函数是最早能够访问data数据和methods中的方法的生命周期函数;
beforeMount()函数之前,Vue开始编译模板,把Vue代码中的指令进行执行,最终在内存中生成一个编译好的模板字符串,然后把这个模板字符串渲染为内存中的DOM。注意:此时只是把模板字符串渲染在内存中,还没有真正挂载在页面上;
beforeMount():此函数执行的时候,模板已经在内存中编译好了,只是没有渲染到页面上,页面中还是旧的模板字符串,没有被真正的数据值替换过来;
mounted():此函数执行时,模板字符串已经真正的挂载在页面中,用户可以看到渲染好的页面,注意:mounted是创建阶段的最后一个生命周期函数,当mounted执行完,表示实例已经创建好了。此时组件脱离创建阶段,进入运行阶段
2、跟新状态:beforeUpdate,update
beforeUpdate():此函数执行时,界面数据还没有更新,但是data中的数据已经更新了,页面尚未和内存中的data同步;
先根据data中最新的数据在内存中重新渲染一份新的DOM树,然后把最新的DOM树渲染到真正的页面中去,就完成了从data(Model)——>view的更新;
updated():此函数执行时,页面data已经和内存中保持同步了,都是最新的
3、销毁vue实例:beforeDestory,destoryed
beforeDestory() :当执行beforeDestory函数时,Vue实例已经从运行阶段进入销毁阶段,当执行beforeDestory时候,data和methods、指令、过滤器还处于可用状态,没有被销毁;
destoryed():当执行destoryed()函数时候,组件已经完全销毁,所有数据都不可用;
其中created/mounted 可以用来发送ajax请求,启动定时器等异步任务
beforeDestroy用来收尾工作,如清除定时器
举个例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>09_Vue实例_生命周期</title>
</head>
<body>
<div id="test">
<button @click="destroyVue">destory vue</button>
<p v-if="isShow">你好</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#test',
data: {
isShow: true
},
beforeCreate() {
console.log('beforeCreate()')
},
created() {
console.log('created()')
},
beforeMount() {
console.log('beforeMount()')
},
mounted () {
console.log('mounted()')
// 执行异步任务
this.intervalId = setInterval(() => {
console.log('-----')
this.isShow = !this.isShow
}, 1000)
},
beforeUpdate() {
console.log('beforeUpdate()')
},
updated () {
console.log('updated()')
},
beforeDestroy() {
console.log('beforeDestroy()')
// 执行收尾的工作
clearInterval(this.intervalId)
},
destroyed() {
console.log('destroyed()')
},
methods: {
destroyVue () {
this.$destroy()//触发 beforeDestroy 和 destroyed 的钩子。
}
}
})
</script>
</body>
</html>运行结果:

更多web开发知识,请查阅 HTML中文网 !!
以上就是destroy什么意思在vue中?的详细内容,更多请关注易知道|edz.cc其它相关文章!














