Vue生命周期钩子

57 阅读1分钟

new vue() 可以创造一个实例 其实所有的组件都是Vue实例 实例化的过程中会默认调用一些函数(Vue默认定义好的),这些函数就叫做钩子

初始化一个项目,里面写上created和mounted方法,发现我们没有调用也会被自动执行,所以我们就可以将想要提前初始化数据写在这些钩子里

<template>
  <div><h1>helloworld</h1></div>
</template>

<script>
export default {
  created() {
    console.log("created");
  },
  mounted() {
    console.log("mounted");
  },
};
</script>

官方文档上的组件生命周期过程图示,红色的都是钩子 请添加图片描述 注意顺序 若想要操作html元素,则create()没啥用

传统写法

<template>
  <div id="app">
    <ul>
      <li v-for="(item, index) of fruits" :key="index">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fruits: ["apple", "pear"],
    };
  },
};
</script>

实际上数据都是异步从服务器获取,应该这样

<template>
  <div id="app">
    <ul>
      <li v-for="(item, index) of fruits" :key="index">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //初始时列表为空
      fruits: [],
    };
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      //通过计数器模拟获取数据
      setTimeout(() => {
        this.fruits = ["apple", "pear"];
      }, 2000);
    },
  },
};
</script>

例子:加载时loading,加载完成不显示loading

<template>
  <div id="app">
    <p v-if="loading">loading</p>
    <ul v-if="!loading">
      <li v-for="(item, index) of fruits" :key="index">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //初始时列表为空
      fruits: [],
      loading: true,
    };
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      //通过计数器模拟获取数据
      setTimeout(() => {
        this.fruits = ["apple", "pear"];
        this.loading = false;
      }, 2000);
    },
  },
};
</script>