Vue 重置組件到初始狀態

Vue 重置組件到初始狀態

Vuevue


經過直接強制刷新 DOM 來達到重置組件的效果,這樣能夠重置一些組件的動畫以及組件內初始的數據

強制從新生成 DOM 的實現

原理:強制從新生成 DOM 能夠經過 Vue 中的 key 來實現。在 Vue 更新 Dom 時,若是 key 值相同則會對原有組件進行復用,若是不一樣,則會從新生成。動畫

代碼示例:this

每次點擊 refresh 按鈕,Demo 組件都會從新生成

組件:code

/**
 * Demo.vue
 */
<template>
  <div>Demo</div>
</template>
<script>
  export default {
    data () {
      return {}
    },
    created: function () {
      console.log('created')
    }
  }
</script>

主頁面:component

/**
 * Index.vue
 */
<template>
  <div>
  <Demo :key="id"></Demo>
  <button @click="refresh">refresh</button>
  </div>
</template>
<script>
  import Demo from './Demo'
  export default {
    data () {
      return {
        id: +new Date()
      }
    },
    methods: {
       refresh: function () {
        this.id = +new Date()
      }
    },
    components: {
      Demo
    }
  }
</script>

注:ip

+new Date() 的說明:
4 個結果同樣,都是返回當前時間的毫秒數
alert(+new Date())
alert(+new Date)
var a=new Date()
alert(a.valueOf())
alert(a.getTime())

Licenseget

  • 能夠拷貝、轉發,可是必須提供原做者信息,同時也不能將本項目用於商業用途。
相關文章
相關標籤/搜索