javascript - Vue.js:在方法中的循环内更新 Bottstrap 进度条
问题描述
我的问题 :
我有一个 Vue.js 方法指令,它声明了一个从 1 到 1.000.000 的循环。我想将我的进度条更新为 50%。因此,当 i == 500000 时,我希望我的 progressBar 的 witdh css 规则为 50%。
这是progressBar的html代码
<div id="app">
<button v-on:click.stop="executeLoop()">Execute the loop</button>
<div class="progress">
<div class="progress-bar progress-bar-striped bg-success"
v-bind:style="barWidthCalculated" v-bind:aria-valuenow="barWidthCalculated"
aria-valuemin="0" aria-valuemax="100">
</div>
</div>
</div>
这是我的 Vue.js 代码
let vm = new Vue({
el: '#app',
data(){ return {
progression : 0,
}},
methods: {
executeLoop: function () {
for (var i = 0; i < 1000000; ++i) {
if (i == 500000) {
this.progression = 50;
//this.$set(this, progression, 30); // This instruction gives me "Reference error: progression is not defined"
}
}
},
},
computed: {
barWidthCalculated: function () {
return {
width: this.progression + '%'
};
}
}
})
解决方案
演示:https ://jsfiddle.net/eywraw8t/183735/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.loader-wrapper {
position: relative;
height: 20px;
background-color: gray;
width: 100%;
text-align: center;
color: #fff;
}
.loader {
position: absolute;
height: 100%;
background-color: rgba(0, 0, 0, .3);
}
</style>
</head>
<body>
<div id="app">
<div class="loader-wrapper">
<div class="loader" :style="{ width: widthPercentage }"></div>
{{ widthPercentage }}
</div>
<button @click="start">Start</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script>
new Vue({
el: "#app",
data: {
width: 0
},
computed: {
widthPercentage() {
return this.width + "%";
}
},
methods: {
start() {
for (let i = 0; i < 1000000; ++i) {
if (i === 500000) {
this.width = 50;
}
}
}
}
})
</script>
</body>
</html>
请注意,这是非常低效的,因为每次点击都会触发这个巨大的循环。此时,循环 10 次或 1000000 次都没有关系,因为渲染仍然需要 1 帧。不同之处在于更大的循环将使该帧需要更长的时间来渲染。
推荐阅读
- java - 如何使用 Gson 从文件中读取参数化列表?
- java - 可以在 tomcat 8 中使用 RolesAllowed 注释吗?
- react-native - 从道具反应原生渲染
- php - 无法访问自动加载库中的函数
- vue.js - Vue.js - 使用具有动态范围值的 v-for
- c# - ComboBox IsChecked 绑定在数据模板中不起作用
- angularjs - 单击 Puppeteer 中的导航按钮返回空响应?如何查看点击了哪个功能?
- javascript - 访问另一个对象内的数组内的对象
- php - 这个 cron 有什么问题?
- javascript - 如何让你的浏览器加速你 bundle.js 的加载?