Vue.js数组更新页面不更新问题小计


在html中根据list动态生成Button,点击每个按钮,改变自身的样式,代码如下:

 <ButtonGroup>
        <Button :type="buttonType[index]" v-for="(item,index) in yearList" :value="item.value" @click="getScore(item.value,index)">{{item.value}}</Button>
      </ButtonGroup>

数据区,定义如下:

 data() {
            return {
                yearList: [],
                year: '',
                buttonType:[]
            }
        },

在方法区域,如果按一般思路写:

this.buttonType[i]=newValue;那么页面是不刷新的,这是Vue框架特点决定的。解决办法有2个:

方法一:采用$set方法

 getScore (year,index) {
              this.year = year;
              for (let i = 0; i < this.buttonType.length; i++) {
                this.$set(this.buttonType,i,'default')
                if (i === index) {
                  this.$set(this.buttonType, i, 'primary')
                }
              }
            },

方法二:采用强制刷新:

 getScore (year,index) {
              this.year = year;
              for (let i = 0; i < this.buttonType.length; i++) {
                this.buttonType[i]='default'
                if (i === index) {
                  this.buttonType[i]='primary'
                }
              }
              this.$forceUpdate();
            },

当然,如果同时采用$set和$forceUpdate()也是可以的。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM