vue生命周期_销毁

在这里插入图片描述

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <style>
    .box {
      height: 1000px
    }
    .button {
      position: fixed;
    }
    .test {
      width: 100px;
      height: 100px;
      border: 1px solid red;
      position: fixed;
      top: 50px;
      left: 50px;
    }
  </style>
</head>
<body>
  <div id="app">
    <button @click="toggle = !toggle">toggle</button>
    <div class="box"></div>
    <Banner v-if="toggle" />
  </div>
  <template id="banner">
    <div class='test' :style="{background: color}">

    </div>
  </div>
  </template>
  <script>
    new Vue({
      el: '#app',
      data: {
        toggle: true
      },
      components: {
        'banner': {
          template: '#banner',
          data () {
            return {
              color: 'rgba(255, 0, 0, .5)'
            }
          },
          methods: {
            changeColor() {
              console.log('改变背景色')
              let r = parseInt(Math.random() * 255)
              let g = parseInt(Math.random() * 255)
              let b = parseInt(Math.random() * 255)
              let a = Math.random()
              this.color = `rgba(${r}, ${g}, ${b}, ${a})`
            }
          },
          created() {
            // 每次 toggle 是 true 的时候 '组件创建' 都会输出
            console.log('组件创建')
            // toggle 每次变成 true 都会在 window 上添加一个 滚支scroll事件 所以要销毁
            window.addEventListener('scroll', this.changeColor)
          },
          beforeDestroy() {
            // 有 dom 元素
            // 全局监听 全局计时器  都要销毁
            console.log('销毁之前')
            window.removeEventListener('scroll', this.changeColor)
          },
          destroy() {
            // 没有 dom 元素
            console.log('销毁结束')
          }
        }
      }
    })
  </script>
  <!-- 
    组件 banner div
    页面滚动的时候背景颜色随机变
    1. 滚动事件
    2. 操作颜色
   -->
</body>
</html>

版权声明:本文为weixin_44166439原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。