VUE从入门到入坑—02.了解生命周期,小练习:对数组的增删改查 / 轮播图


上篇:01.初识Vue:安装/常用指令/响应式原理/条件渲染/列表渲染
下篇:03.VUE从入门到入坑—03.样式绑定 / 计算属性 / 监听|侦听器 / 局部|全局过滤器

一、什么是生命周期

当我们执行 new Vue() 开始到被创建完成,vue需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做生命周期钩子的函数,这给了用户在不同阶段添加自己的代码的机会。

1.beforeCreate 创建之前 (数据初始化之前),Vue实例,已经创建完成,但是Vue实例身上的数据还没有初始化完成。此生命周期函数,基本上不用,除非要设置Vue实例的本身。

2.created 创建完成 (数据初始化完成),这个生命周期,通常用于初始化Vue管理的数据 比如发送Ajax请求会放在这里。√

3.beforeMount 挂载之前 (模板已经成功渲染,但是还没有将内容挂载到页面中),这个生命周期函数,基本上不用。

4.mounted 挂载完成(模板已经成功渲染,并且已经将模板内容挂载到了页面),这个生命周期函数,通常用于对Dom的重新改动。√

5.beforeUpdate 修改之前 (数组已经改了,只是还没有重新挂载页面)

6.updated 修改完成 (数组已经改了,页面也已经重新挂载)

7.beforeDestroy 销毁之前,这个生命周期函数,会用的多一些。但是此时对数据做任何的修改,都不会重新渲染到页面。√

8.destroyed 销毁完成,此时对数据做任何的修改,都不会重新渲染到页面。这个生命周期函数,几乎不用。

9.destroy 调用销毁当前Vue实例的方法。

<body>
    <div id="app">
        <h2 id="name">{{name}}</h2>
        <h2 id="age">{{age}}</h2>
        <div>
            <button @click='name="李四"'>修改姓名</button>
            <button @click='age="30"'>修改年龄</button>
            <button @click='destroy'>不过了</button>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.js"></script>
    <script>
        Vue.config.productionTip = false
        let mx = new Vue({
            // 指定挂载的容器。
            // el:'#app',
            // 指定模板 (如果有模板,vue会渲染整个模板;如果没有模板,vue会将el里面的所有内容当成模板使用)
            // template:'<div><h2>{{name}}</h2><h2>{{age}}</h2></div>',
            data:{
                name:'张三',
                age:20,
                // list:[]
            },
            methods: {
                destroy(){
                    // 调用销毁当前Vue实例的方法
                    // 注意:销毁后,当前Vue实例对象还在,只是不该对象不能再重新挂载页面了
                    this.$destroy()
                }
            },
            // 创建之前(数据初始化之前)
            beforeCreate() {
                console.log('------------------beforeCreate----------------');
                // 这个生命周期函数,基本上不用,除非要设置Vue实例的内容。
                this.__proto__.fn = function(){
                    alert('哈哈!')
                }
                // Vue实例,已经创建完成
                console.log(this);
                // Vue实例身上的数据还没有初始化完成。
                console.log(this.name,this.age);
            },


            // 创建完成(数据初始化完成)
            // √
            created() {
                console.log('------------------created----------------');
                // 这个生命周期,通常用于初始化Vue管理的数据 比如发送Ajax请求会放在这里。
                console.log(this);
                console.log(this.name,this.age);
                // let data = axios.get('')
                // this.list = data
                

            },
            //挂载之前(模板已经成功渲染,但是还没有将内容挂载到页面中)
            beforeMount() {
                console.log('------------------beforeMount----------------');
                // console.log(this);
                // 这个生命周期函数,基本上不用。
                console.log(this.$el);

              
            },
            //挂载完成(模板已经成功渲染,并且已经将模板内容挂载到了页面)
            // √
            mounted() {
                console.log('------------------mounted----------------');
                //这个生命周期函数,通常用于对Dom的重新改动
                console.log(this.$el);
                // document.querySelector('#name').innerHTML='哈哈'
            },
            // 修改之前 (数组已经改了,只是还没有重新挂载页面)
            // 
            beforeUpdate() {
                console.log('------------------beforeUpdate----------------');
                console.log(this.name,this.age);
                console.log(this.$el);
                // debugger
            },
            // 修改完成 (数组已经改了,页面也已经重新挂载)
            updated() {
                console.log('------------------updated----------------');
                console.log(this.name,this.age);
                console.log(this.$el);
            },
            // 销毁之前() 
            // √
            beforeDestroy() {
                console.log('------------------beforeDestroy----------------');
                // 这个生命周期函数,会用的多一些。
                console.log(this);
                //此时对数据做任何的修改,都不会重新渲染到页面。
                this.name = '王五'
                
            },
            //销毁完成()
            destroyed() {
                console.log('------------------destroyed----------------');
                // 这个生命周期函数,几乎不用。
                console.log(this);
                //此时对数据做任何的修改,都不会重新渲染到页面。
                this.name = '王五'
            },
        })
        // 通过VUE实例的$mount方法,手动挂载容器。
        // 通过el选项指定挂载容器,当模板渲染成功后,会立刻挂载页面。
        // $mount方法的好处是,可以自行选择挂载的时机。
        setTimeout(()=>{
            mx.$mount('#app')
        },1000)
    </script>
</body>

生命周期中文图示

二、指定模板与指定挂载的容器

            // 指定挂载的容器。
            // el:'#app',
            // 指定模板 (如果有模板,vue会渲染整个模板;如果没有模板,vue会将el里面的所有内容当成模板使用)
            // template:'<div><h2>{{name}}</h2><h2>{{age}}</h2></div>',

三、$mount方法,手动挂载容器

        ***通过VUE实例的$mount方法,手动挂载容器
        通过el选项指定挂载容器,当模板渲染成功后,会立刻挂载页面。
        $mount方法的好处是,可以自行选择挂载的时机。***
        setTimeout(()=>{
            mx.$mount('#app')
        },1000)

四、使用Vue实现对数组的增删改查

<!DOCTYPE html>
<html>
<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>使用vue实现对数组的增删改查</title>
    <style>
        table{
            border-collapse: collapse;
        }
        th,td{
            padding: 2px 15px;
            border: 1px solid #ccc;
            text-align: center;
        }
        #edit{
            width: 300px;
            height: 230px;
            border: 1px solid #ccc;
            padding: 20px;
            position: fixed;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        }
        #edit .close{
            width: 30px;
            height: 30px;
            border: 1px solid #ccc;
            background-color: lightcoral;
            color: white;
            text-align: center;
            line-height: 30px;
            font-size: 20px;
            border-radius: 50%;
            cursor: pointer;
            position: absolute;
            right: 10px;
            top: 10px;
        }
    </style>
</head>
<body>
    <div id="app">
        <button @click="showEdit=true">添加</button>
        <hr>
        <table>
            <thead>
                <tr>
                    <th>学号</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item,index) in students" :key="index">
                    <td>{{item.no}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.age}}</td>
                    <td>{{item.sex}}</td>
                    <td>
                        <button @click="getOne(item.no)">修改</button>
                        <button @click="delStudent(index)">删除</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <div id="edit" v-show="showEdit">
            <!-- 在修改界面中,不能修改学号 -->
            <p>学号:<input type="text" v-model="student.no" :readonly="!isAdd"></p>
            <p>姓名:<input type="text" v-model="student.name"></p>
            <p>年龄:<input type="text" v-model="student.age"></p>
            <p>性别:<input type="text" v-model="student.sex"></p>
            <p>
                <button v-if="isAdd" @click="addStudent">添加</button>
                <button v-else @click="updateStudent">修改</button>
                <button @click="clear">取消</button>
            </p>
            <div class="close" @click="close">X</div>
        </div>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
    <script>
        new Vue({
            el:'#app',
            data:{
                //定义一个学生数组
                students:[
                    {
                        no:'1001',
                        name:'刘德华',
                        age:20,
                        sex:'男'
                    },
                    {
                        no:'1002',
                        name:'周杰伦',
                        age:22,
                        sex:'男'
                    },
                    {
                        no:'1003',
                        name:'蔡依林',
                        age:24,
                        sex:'女'
                    }
                ],
                //是否显示编辑窗口
                showEdit:false,
                //是否是添加状态
                isAdd:true,
                //学生对象
                student:{
                    no:'',
                    name:'',
                    age:0,
                    sex:''
                }
            },
            methods: {
                //添加方法
                addStudent(){
                    //将表单数据展开后,返回一个新的对象
                    let stu = {...this.student} 
                    //将学生对象添加到学生数组中
                    this.students.push(stu)
                    //调用清空表单数据的方法
                    this.clear()
                },
                //清空表单数据的方法
                clear(){
                    this.student = {
                        no:'',
                        name:'',
                        age:0,
                        sex:''
                    }
                },
                //关闭编辑窗口
                close(){
                    this.showEdit = false
                    this.isAdd = true
                    this.clear()
                },
                //根据学号查询学生对象
                getOne(no){
                    //打开编辑窗口
                    this.showEdit = true
                    //编辑窗口是修改状态
                    this.isAdd = false
                    //根据学号查询学生对象
                    let stu = this.students.find(s=>s.no===no)
                    this.student = {...stu}
                },
                //修改学生信息
                updateStudent(){
                    //根据学号,找到原始数组中指定的学生对象
                    let stu = this.students.find(s=>s.no===this.student.no)
                    //修改数组里面指定学生对象的属性
                    stu.name = this.student.name
                    stu.age = this.student.age
                    stu.sex = this.student.sex
                },
                //删除学生
                delStudent(index){
                    if(confirm('确定删除吗?')){
                        this.students.splice(index,1)
                    }
                }
            },
        })
    </script>
</body>
</html>

五、再来个小练习:轮播图,over,期待下次更新

<!DOCTYPE html>
<html>

<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>
    <style>
        #app {
            position: relative;
            width: 750px;
        }

        #app img {
            width: 100%;
        }

        .jiantou {
            width: 50px;
            height: 50px;
            background-color: rgba(0, 0, 0, 0.50);
            position: absolute;
            top: 0;
            bottom: 0;
            margin: auto 0;
            font-size: 30px;
            text-align: center;
            line-height: 50px;
            color: white;
            cursor: pointer;
        }

        .left {
            left: 10px;
        }

        .right {
            right: 10px;
        }
    </style>
</head>

<body>
    <div id="app" @mouseenter="mouseenter" @mouseleave="mouseleave">
        <img :src="imgs[showActive]">
        <div class="left jiantou" @click="left">←</div>
        <div class="right jiantou" @click="right">→</div>
        <button @click="destroy">终止播放</button>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
    <script>
        Vue.config.productionTip = false
        new Vue({
            el: '#app',
            data: {
                //定义定时器
                timer: null,
                //显示的下标
                showActive: 0,
                //图片数组
                imgs: ["http://p1.music.126.net/7zAkp74zoKd0LuEuEP6dOg==/109951166645160829.jpg?imageView&quality=89",
                    "http://p1.music.126.net/pkXsmqmFQOehNkJYmehkng==/109951166646695577.jpg?imageView&quality=89",
                    "http://p1.music.126.net/c1olbeIgiVsj9I39fCUXkQ==/109951166644891380.jpg?imageView&quality=89",
                    "http://p1.music.126.net/JMYet32O1mi6-YZ1GGSYcQ==/109951166646419732.jpg?imageView&quality=89",
                    "http://p1.music.126.net/WCX5Cq1z17Du2z0QBEcEaA==/109951166645933077.jpg?imageView&quality=89"]
            },
            methods: {
                left() {
                    this.showActive--
                    //如果下标越界,重新从0开始
                    if (this.showActive < 0) this.showActive = 4
                },
                right() {
                    this.showActive++
                    //如果下标越界,重新从0开始
                    if (this.showActive >= 5) this.showActive = 0
                },
                mouseenter() {
                    clearInterval(this.timer)
                },
                mouseleave() {
                    //开启定时器
                    this.run()
                },
                run() {
                    this.timer = setInterval(() => {
                        console.log(11);
                        this.showActive++
                        //如果下标越界,重新从0开始
                        if (this.showActive >= 5) this.showActive = 0
                    }, 1000);
                },
                destroy(){
                    this.$destroy()
                }
            },
            //生命周期函数(表示页面挂载完成)
            mounted() {
                //开启定时器
                this.run()
            },
            // 在这个生命周期函数中,清除定时器
            beforeDestroy() {
                clearInterval(this.timer)
            },
        })
    </script>
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,175评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,674评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,151评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,597评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,505评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,969评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,455评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,118评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,227评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,213评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,214评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,928评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,512评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,616评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,848评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,228评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,772评论 2 339

推荐阅读更多精彩内容