Vue中$forceUpdate()的使用

在Vue官方文档中指出,$forceUpdate具有强制刷新的作用。

那在vue框架中,如果data中有一个变量:age,修改他,页面会自动更新。
但如果data中的变量为数组或对象,我们直接去给某个对象或数组添加属性,页面是识别不到的.

<template>
  <p>{
    
    {
    
    userInfo.name}}</p>
  <button @click="updateName">修改userInfo</button>
</template>
<script>
  data(){
    
    
    return{
    
    
      userInfo:{
    
    name:'小明'}
    }
  },
  methods:{
    
    
    updateName(){
    
    
      this.userInfo.name='小红'
    }
  }
</script>

在updateName函数中,我们尝试给userInfo对象修改值,发现页面其实并没有变化
那这时候有两种解决方法:

方法一:

methods:{
    
    
  updateName(){
    
    
    this.userInfo.name='小红'//在此时,确实已经将userInfo对象修改完成
    console.log(this.userInfo.name);//输出结果: 小红
    this.$forceUpdate();//在这里,强制刷新之后,页面的结果变为'小红'
  }
}

方法二:

methods:{
    
    
  updateName(){
    
    
    this.$set('userInfo',name,'小红');
  }
}

猜你喜欢

转载自blog.csdn.net/zch981964/article/details/128713360