gpt4 book ai didi

javascript - 通过按钮运行计算函数,通过 v-bind 指令更改 CSS 类

转载 作者:行者123 更新时间:2023-11-27 23:03:22 25 4
gpt4 key购买 nike

我正在尝试运行一个改变 width 的函数的 <div>通过按钮随机触发功能,使用 vuejs

当我第一次测试该功能时,没有使用 :style="width"我用的是 :style="lifeBar"在我的 <div>每次我运行代码时,条形图的宽度都会随机改变。换句话说,该功能运行良好。

这是我的代码:

HTML

<div id="app">
<div :style="width"
class="healthbar text-center"
style="background-color: green;
margin: 0; color: white; width: 100%">
</div>
//I just could not figure out what to do below to make the function run on the div above
<button @click="lifeBar">testing random</button>
</div>

JS

new Vue({
el: "#app",
data: {
width: 100
},
computed: {
lifeBar: function() {
var rand = Math.floor(Math.random()*100)
return {width: rand + '%'}
}
}
})

我想弄清楚的是如何触发此函数来修改 width每次我点击button

提前感谢大家!

最佳答案

最好的办法是在单击时调用一个方法,该方法更新一个数据值,然后您的计算将使用该数据值返回 CSS。这看起来像这样:

<div :style="lifeBar">
[...]
</div>
<button @click="setWidth">testing random</button>
new Vue({
el: "#app",
data: {
width: 100
},
methods: {
setWidth() {
this.width = Math.floor(Math.random() * 100);
}
},
computed: {
lifeBar() {
return {
width: `${this.width}%`;
}
}
}
})

关于javascript - 通过按钮运行计算函数,通过 v-bind 指令更改 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58860496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com