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