这次给大家带来vue组件生命周期使用方法,vue组件生命周期使用的注意事项有哪些,下面就是实战案例,一起来看一下。
分为4个阶段:
create/mount/update/destroy
每一个阶段都对应着有自己的处理函数
create: beforeCreate created
初始化
mount: beforeMount mounted
和挂载相关的处理
update: beforeUpdate updated
根据要更新的数据 做逻辑判断
destroy:beforeDestroy destroyed
清理工作
代码:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>生命周期</title>
<script src="js/vue.js"></script>
</head>
<body>
<p id="container">
<p>{{msg}}</p>
<!--点击的时候isShow进行取反 -->
<button @click="isShow = !isShow">切换是否显示组件</button>
<my-component v-if="isShow"></my-component>
</p>
<script>
Vue.component("my-component",{
template:`
<p>
<button @click="handleClick">Click Me</button>
<h1>component:{{count}}</h1>
</p>
`,
data:function(){
return {
count:0
}
},
methods:{
handleClick:function(){
this.count++;
}
},
beforeCreate: function () {
console.log('准备创建组件');
},
created: function () {
console.log('组件创建完毕');
},
beforeMount: function () {
console.log('组件的模板准备挂载到DOM');
},
mounted: function () {
console.log('挂载完毕');
},
beforeUpdate: function () {
console.log('准备更新了');
},
updated:function(){
console.log('更新完成');
},
beforeDestroy: function () {
console.log('准备destroy');
},
destroyed: function () {
console.log('destroy完成');
}
})
new Vue({
el:"#container",
data:{
msg:"Hello VueJs",
isShow:true
}
})
</script>
</body>
</html>生命周期练习,需要那阶段写那个阶段
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>生命周期练习</title>
<script src="js/vue.js"></script>
</head>
<body>
<p id="container">
<p>{{msg}}</p>
<my-component></my-component>
</p>
<script>
Vue.component("my-component",{
data:function(){
return {
myOpacity:0
}
},
template:` <h1 v-bind:style="{opacity:myOpacity}">透明度将改变
</h1>`,
mounted:function(){
setInterval(function(){
this.myOpacity += 0.1;
if(this.myOpacity>1){
this.myOpacity = 0;
}
}.bind(this),1000)
}
})
new Vue({
el:"#container",
data:{
msg:"Hello VueJs"
}
})
</script>
</body>
</html>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
立即学习“前端免费学习笔记(深入)”;
以上就是vue组件生命周期使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号