Vue2 中重新加载组件的方法

location. reload()和this.$router.go(0)

location. reload()和this.$router.go(0)都可以刷新当前页面的,缺点就是相当于按ctrl+F5 强制刷新,整个页面重新加载,会出现一个瞬间的空白页面,体验不好。

v-if可以实现 true (加载)和false(卸载)

使用v-if加上变量的形式来控制组件的加载与销毁,好处在于可以在父组件中通过某个变量来控制子组件的渲染,打开的时候子组件会触发beforeCreate、created、beforeMount、mounted四个生命周期,关闭的时候子组件会触发beforeDestroy、destroyed两个生命周期,因此在某些操作中如果需要通过某个变量的内容来对子组件进行生命周期的刷新,即可用v-if来进行显隐操作。

forceUpdate()

Vue中可以通过强制更新(forceUpdate)来重新加载组件。forceUpdate方法会强制组件重新渲染,不会触发组件生命周期的beforeUpdate和updated等钩子函数。因此,建议在没有其他更合适的方法时才使用forceUpdate。
先修改下message的值,在调用forceUpdate,message的值会变回原样。

<template>
  <div>
    <p>{{message}}</p>
    <button @click="changeMessage">修改信息</button>
    <button @click="handleClick">重新加载</button>
  </div>
</template>
<script>
  export default {
    name: 'MyComponent',
    data() {
      return {
        message: '初始化数据'
      }
    },
    methods: {
    	changeMessage(){
    	this.message = '变色'
    	},
     	handleClick() {
        this.$forceUpdate();
      }
    }
  }
</script>

使用 key 属性

在组件中添加 key 属性,通过修改 key 的值来重新加载组件。当 key 的值变化时,Vue 会强制重新渲染并加载新的组件

<template>
  <div :key="componentKey">
    <MyComponent />
  </div>
</template>
<script>
import MyComponent from './MyComponent.vue'
export default {
  components: { MyComponent },
  data() {
    return {
      componentKey: 0 // 初始 key 值为 0
    }
  },
  methods: {
    reloadComponent() {
      this.componentKey++ // 修改 key 值来重新加载组件
    }
  }
}
</script>

这里的 key 属性绑定了组件外层的 div 元素上,当调用 reloadComponent 方法时,会修改 componentKey 的值,从而重新渲染并加载 MyComponent 组件。

使用动态组件

使用 Vue 的 元素来实现动态组件加载。当这个元素的 is 属性发生变化时,它会切换当前显示的组件。

<template>
  <div>
    <component :is="currentComponent"></component>
  </div>
</template>
<script>
import MyComponent from './MyComponent.vue'
export default {
  data() {
    return {
      currentComponent: 'MyComponent' // 初始显示 MyComponent 组件
    }
  },
  methods: {
    reloadComponent() {
      this.currentComponent = null // 先把当前组件置为 null
      this.$nextTick(() => {
        this.currentComponent = MyComponent // 然后再把要加载的组件赋值给 currentComponent
      })
    }
  },
  components: {
    MyComponent
  }
}
</script>

这里定义了一个 currentComponent 变量来绑定 元素的 is 属性。当调用 reloadComponent 方法时,先把 currentComponent 置为 null,这会强制 元素重新渲染,然后在 $nextTick 回调中把要重新加载的组件赋值给 currentComponent 即可。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值