Vue基础05生命周期

107 阅读1分钟

Vue基础05生命周期

介绍Vue生命周期的概念及应用

什么是生命周期?

每个Vue实例在被创建时都要经过一系列的初始化过程,例如需要设置数据监听、编译模板、将实例挂载到DOM并在数据变化时更新DOM等,称为Vue实例的生命周期。

1 生命周期应用

在Vue实例的生命周期过程中会运行一些叫做生命周期钩子的函数,可以在不同阶段添加自己的代码

模拟异步数据调用

2个生命周期的钩子比较常用

  1. created()

  2. mounted()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
</head>
<body>
    <div id="app">
        <h2>{{title}}</h2>

        <input v-model="course" v-on:keydown.enter="addCourse"> 
        <button @click="addCourse">新增</button>

        <div v-for="item in courses" :key="item">
            {{ item }}
        </div>
        <div>课程总数:{{this.courses.length}}门</div>
    </div>

    <script src="../js/vue.js"></script>

    <script>

        // 模拟异步数据调用
        function getCourses() {
            return new Promise(resolve => {
                setTimeout(() => {
                    resolve(['Java课程', 'Web课程', '爬虫课程' ])
                }, 1000)
            })
        }

        const app = new Vue({
            el: '#app',
            data() {
                return {
                    title: '购物车',
                    courses: [],
                    course: '',
                    selectedCourse: ''
                }
            },
            async created() {
                const courses = await getCourses()
                this.courses = courses
            },
            methods: {
                addCourse() {
                    if (this.course == '' || this.courses.indexOf(this.course) > -1) {
                        return
                    }
                    this.courses.push(this.course)
                    this.course = ''
                }
            }
        })
    </script>
</body>
</html>

2 生命周期探讨

{
	// 阶段一:初始化
  beforeCreate(){} // 组件实例未创建,通常用于插件开发中执行一些初始化任务
  created(){} // 组件初始化完毕,各种数据可以使用,常用于异步数据获取
  beforeMount(){} // 未执行渲染、更新,dom未创建
  mounted(){} // dom已创建,可用于获取访问数据和dom元素

	// 阶段二:更新
  beforeUpdate(){} // 更新前,用于获取更新前各种状态
  updated(){} // 更新后,所有状态已是最新

	// 阶段三:销毁
	beforeDestroy(){} // 销毁前,可用于一些定时器或订阅的取消
  destroyed(){} // 组件已销毁
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h1>初始化流程</h1>
        {{foo}}
    </div>
    <script src="../js/vue.js"></script>
    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    foo: 'foo value'
                }
            },
            beforeCreate () {
                console.log('beforeCreate');
            },
            created () {
                console.log('created', this.$el);
            },
            beforeMount () {
                console.log('beforeMount');
            },
            mounted () {
                setTimeout(() => {
                    this.foo = 'foo value changed'
                }, 2000);
                console.log('mounted', this.$el);
            },
            beforeUpdate () {
                console.log('beforeUpdate');
            },
            updated () {
                console.log('updated');
            },
            beforeDestroy () {
                console.log('beforeDestroy');
            },
            destroyed () {
                console.log('destroyed');
            },
        })
    </script>
</body>
</html>