『VUE』31. 生命周期的应用(详细图文注释)
目录
- 在合适的时间进行操作
- 取dom元素
- 利用生命周期模拟网络数据发送
- 代码示例
- 总结
欢迎关注 『VUE』 专栏,持续更新中
欢迎关注 『VUE』 专栏,持续更新中
在合适的时间进行操作
假设网页一颗果树,我们要取dom(果实),一定要在渲染完成后才能取(果实)
通常是在组件挂载完毕mounted()
(果子成熟了)取较为合适.
取dom元素
beforeMount()挂载之前,underfind
mounted()挂载完毕,才能拿到dom
app.vue
<template><h3>生命周期</h3><p ref="msg">{{ message }}</p><button @click="updatedData">修改数据</button>
</template><script>
export default {data() {return {message: "qwer",};},methods: {updatedData() {this.message = this.message + "asdf";},},beforeCreate() {console.log("创建之前~");},created() {console.log("创建完毕");},beforeMount() {console.log("挂载之前");console.log(this.$refs.msg); //underfind},mounted() {console.log("挂载完毕");console.log(this.$refs.msg);},beforeUpdate() {console.log("更新之前");},updated() {console.log("更新完毕");},beforeUnmount() {console.log("销毁之前");},unmounted() {console.log("销毁完毕");},
};
</script>
利用生命周期模拟网络数据发送
一个常用的应用是我们接收到一组json数据,然后在前端可视化,在我们挂载完毕的生命周期后进行渲染.所以通过在挂载完毕后加入数据的方式,模拟网络数据发送到网页的过程.
data数据初始化是在create之后的,表示数据初始化完毕,所以我们created()中赋值数据,实际开发中不是赋值是从某些接口获取.
created() {console.log("创建完毕");this.banner = [{title: "mzh",content: "wg191",},{title: "ljc",content: "wg191",},{title: "ltl",content: "wg191",},];},
但是你也可以放在mounted()表示结构已经渲染完成,一般来说结构更重要,类似京东的下拉刷新商品,可以看到结构是已经有了的,但是数据是稍后出现的.
代码示例
<template><h3>生命周期</h3><p ref="msg">{{ message }}</p><button @click="updatedData">修改数据</button><ul><li v-for="(item, index) of banner" :key="index"><h3>{{ item.title }}</h3><h3>{{ item.content }}</h3></li></ul>
</template><script>
export default {data() {return {message: "qwer",banner: [],};},methods: {updatedData() {this.message = this.message + "asdf";},},beforeCreate() {console.log("创建之前~");},created() {console.log("创建完毕");},beforeMount() {console.log("挂载之前");console.log(this.$refs.msg); //underfind},mounted() {console.log("挂载完毕");console.log(this.$refs.msg);this.banner = [{title: "mzh",content: "wg191",},{title: "ljc",content: "wg191",},{title: "ltl",content: "wg191",},];},beforeUpdate() {console.log("更新之前");},updated() {console.log("更新完毕");},beforeUnmount() {console.log("销毁之前");},unmounted() {console.log("销毁完毕");},
};
</script>
总结
大家喜欢的话,给个👍,点个关注!给大家分享更多计算机专业学生的求学之路!
版权声明:
发现你走远了@mzh原创作品,转载必须标注原文链接
Copyright 2024 mzh
Crated:2024-3-1
欢迎关注 『VUE』 专栏,持续更新中
欢迎关注 『VUE』 专栏,持续更新中
『未完待续』