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()也是可以的。

posted @ 2020-06-15 16:07  Shapley  阅读(1276)  评论(0编辑  收藏  举报