【Vue3 从入门到实战 进阶式掌握完整知识体系】036-Composition API:生命周期函数新写法

398 阅读1分钟

7、生命周期函数新写法

简单使用

非常简单,其他生命周期函数就省略了

<!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>hello</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    setup(){
      const { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated } = Vue;
      const num = ref(111);
      onBeforeMount(() => {
        console.log("onBeforeMount");
      });
      onMounted(() => {
        console.log("onMounted");
      });
      onBeforeUpdate(() => {
        console.log("onBeforeUpdate");
      });
      onUpdated(() => {
        console.log("onUpdated");
      });

      return{ num }
    },
    template: `
      <div>
        Hello World!
        {{num}}
        <input v-model="num" />
      </div>
    `
  });
  
  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210616205036000