vue的生命周期

1:概念了解

Vue实例有一个完整的生命周期,也就是从开始创建、初始化数据、编译模板、挂载Dom、渲染→更新→渲染、卸载等一系列过程,我们称这是Vue的生命周期。通俗说就是Vue实例从创建到销毁的过程,就是生命周期。

2:了解

(1).beforeCreate
在实例初始化之后,数据观测(data observer) 和 event/watcher 事件配置之前被调用。


beforeCreate() {
   console.log(this.page); // undefined
   console.log{this.showPage); // undefined
 },
 data() {
   return {
     page: 123
   }
 },
 methods: {
   showPage() {
     console.log(this.page);
   }
 }

解释:这个时期,this变量还不能使用,在data下的数据,和methods下的方法,watcher中的事件都不能获得到;

(2).created
实例已经创建完成之后被调用。在这一步,实例已完成以下的配置:数据观测(data observer),属性和方法的运算, watch/event 事件回调。然而,挂载阶段还没开始,$el 属性目前不可见。

created() {
   console.log(this.page); // 123
   console.log{this.showPage); // ...
   $('select').select2(); // jQuery插件需要操作相关dom,不会起作用
 },
 data() {
   return {
     page: 123
   }
 },
 methods: {
   showPage() {
     console.log(this.page);
   }
 }

(3).beforeMounte
在挂载开始之前被调用:相关的 render 函数首次被调用。
(4).mounted
mounted el 挂载到实例上后调用,有DOM,有数据。

钩子函数区别:

个人理解:
Created 创建。有数据,有方法,没有挂载,没有DOM
Mounted 挂载。有DOM,有数据
Beforecreated 创建之前。没有数据,没有方法
Beforemounted 挂载之前,没有DOM,有数据
Beforedestroy 实例销毁之前

路由跳转参数,及接受参数this.$route.params.id

<template>
    <div>
     <h1>学习从现在开始</h1>
      <ul>
        <li v-for="item in bloglist">
          <router-link :to="'/Hello/'+ item.id">
            {{item.title}}</router-link>
        </li>
      </ul>
    </div>
</template>
<script>
    export default {
      data(){
        return{
          bloglist:[
            {id:1, title:'hello world'},
            {id:2, title:'js基础知识'},
            {id:3, title:'CSS基础知识'},
            {id:4, title:'HTML基础知识'},
          ]
        }
      }
    }
</script>
<style scoped>
</style>
<template>
    <div>
      <h1>博客详情:{{$route.params.id}}</h1>
      <p>{{blogContent}}</p>
      <button @click="$router.go(-1)">点击返回上一页</button>
    </div>
</template>

<script>
    export default {
      data(){
        return{
          blogContent:''
        }
      },
      created() {
        console.log('this.$route',this.$route)
        let id = this.$route.params.id;
        this.getBlogDateById(id);
      },
      methods: {
         getBlogDateById(id) {
           switch (id) {
             case '1':this.blogContent = "地狱世界";
             case '2':this.blogContent = "对网页行为进行编程";
             case '3':this.blogContent = "规定网页的布局";
             case '4':this.blogContent = "定义网页的内容";
           }
         }
      }
    }
</script>

<style scoped>

</style>

        
点击任何一个小标题

对应相应的内容

1.传参数方式可分为params传参和query传参,通过router-link组件的to属性实现,子路由需要提前配置好参数。
2.大致看了一下(未做相关练习熟悉)
computed和watch的区别和应用场景
vuex状态管理
自定义组件

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容