vue组件的局部刷新

684 阅读1分钟

通过 provide/inject 实现子路由的局部刷新

  • 父组件
    <router-view v-if="isRouterAlive"></router-view>
    
    data () {
      return {
        isRouterAlive: true
      }
    },
    provide() {
      return {
        reload: this.reload
      }
    },
    methods: {
      reload() {
        this.isRouterAlive = false
        this.$nextTick(() => {
          this.isRouterAlive = true
        })
      }
    }
    
  • 子孙组件
    // 子孙组件
    inject: ['reload'],
    methods: {
      // 刷新
      refresh() {
        this.reload()
      }
    }
    

通过 v-if 实现组件的局部刷新

<div v-if="isShow"></div>

data () {
  return {
    isShow: true
  }
},
methods: {
  refresh() {
    this.isShow = false
    this.$nextTick(() => {
      this.isShow = true
    })
  }
}

通过 key 值的变化触发组件的局部更新

<div :key="keyNum"></div>

data () {
  return {
    keyNum: true
  }
},
methods: {
  refresh() {
    this.keyNum++
  }
}