Vue JS将一个值传递给CSS属性

时间:2018-03-05 06:06:49

标签: vue.js vuejs2 vue-component

我正在开发一个考试门户网站应用程序。

enter image description here

这是我的代码。

<div class="" v-for="areas in knowledgeAreas">
        {{areas.area}}<div class="progress"  style="margin-top:10px;">
          <div class="progress-bar"  style="width:50%">{{areas.correctlyMarkedAnswers}} out of {{areas.numberOfQuestion}}</div>
        </div>

      </div>

data(){
    return{
      knowledgeAreas :[
        { area: 'Math',numberOfQuestion:10,correctlyMarkedAnswers:3,correctAnswersPercentage:12 },
        { area: 'IQ',numberOfQuestion:10,correctlyMarkedAnswers:5,correctAnswersPercentage:5 },
        { area: 'GK',numberOfQuestion:10,correctlyMarkedAnswers:8,correctAnswersPercentage:3 }
      ]
    }
  }

我想要的是动态地将correctAnswersPercentage属性的值传递给CSS width属性。

1 个答案:

答案 0 :(得分:3)

我创建了getProgress方法,然后在迭代期间传递correctAnswersPercentage的值。

请查看以下代码段:

new Vue({
	el: "#app",
  data: {
      knowledgeAreas :[
        { area: 'Math',numberOfQuestion:10,correctlyMarkedAnswers:3,correctAnswersPercentage:50 },
        { area: 'IQ',numberOfQuestion:10,correctlyMarkedAnswers:5,correctAnswersPercentage:60 },
        { area: 'GK',numberOfQuestion:10,correctlyMarkedAnswers:8,correctAnswersPercentage:70 }
      ]
    },
    methods: {
    	getProgress: function(width) {
      	return {
          'width': width + '%',
          'background-color': 'yellow'
        };
      }
    }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
<div id="app">
<div class="" v-for="areas in knowledgeAreas">
        {{areas.area}}<div class="progress"  style="margin-top:10px;">
          <div class="progress-bar"  v-bind:style="getProgress(areas.correctAnswersPercentage)">{{areas.correctlyMarkedAnswers}} out of {{areas.numberOfQuestion}}</div>
        </div>
      </div>
</div>