crazyones110
2/3/2020 - 10:27 AM

环境中只创建一个东西

创建的时候如何判断时候已经存在了,然后创建新的 保证环境中只有一个,不能有多个

<script>
  export default {
    data() {
      return {
        currentDiv: null
      }
    },
    methods: {
      createDiv() {
        if (!this.currentDiv) {
          const div = document.createElement('div')
          div.id = 'test-div'
          div.innerText = parseInt(Math.random() * 100)
          document.body.appendChild(div)
          this.currentDiv = div
        } else {
          this.currentDiv.remove()
          const div = document.createElement('div')
          div.id = 'test-div'
          div.innerText = parseInt(Math.random() * 100)
          document.body.appendChild(div)
          this.currentDiv = div
        }
      }
    }
  }
</script>