Vue中,$forceUpdate()的使用(针对列入多选下拉框回显无法重新编辑

Vue中,$forceUpdate()的使用

方文档中指出,$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,'小红');
  }
}

 

本文作者:独自一人的江湖

本文链接:https://www.cnblogs.com/dream-007/p/18550264

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   独自一人的江湖  阅读(175)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
🔑