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

标签 javascript css vuejs2

我正在尝试运行一个改变 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/

相关文章:

javascript - 我如何要求用户确认他们要离开页面?

Javascript Push() 方法更改引用数组中的值

javascript - 从另一个 React 文件调用函数

CSS 动画 : different cubic-bezier

javascript - Vue : sort array based on object order

javascript - 数组和异步函数回调

javascript - 如何在JQuery 中只获取无序列表菜单中的第一个列表元素?

css - 在输入类型文本中包含真棒字体

vue.js - 将 Vue 与编辑器一起使用

javascript - Vue.js:v-for 超过对象会导致键的顺序错误