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