我想将一个动态变量传递给样式,这可能吗?我试过这种方法,但没有用:
:style="{'width':`${parseInt(100 * task.progress)}`% ;}"
这是我的task.vue:
<tr v-for="task in tasks.data " v-if=" task.projet_id == key " :key="task.id">
<td >{{ parseInt(100 * task.progress) }}% <div class="progress">
<div class="progress-bar bg-success" role="progressbar" aria-valuenow="0" :style="
{'width':`${parseInt(100 * task.progress)}`% ;}" id="progress"
aria-valuemin="`${parseInt(100 * task.progress)}`" aria-valuemax="100"></div>
</div>
</td>
最佳答案
有sure is a way做你正在寻找的东西,我为你链接了一个演示。
让我们看得更深
我们可以看看你的v-bind
语法
<div class="progress-bar bg-success" role="progressbar" aria-valuenow="0" :style="
{'width':`${parseInt(100 * task.progress)}`% ;}" id="progress"
aria-valuemin="`${parseInt(100 * task.progress)}`" aria-valuemax="100"></div>
</div>
我会稍微简化一下
<div
:style="{'width':`${parseInt(100 * task.progress)}`% ;}">
</div>
在这里我可以看到你已经绑定(bind) style
到expression
{'width':`${parseInt(100 * task.progress)}`% ;}
我们可以看到您正在创建一个 Object
键 width
并且其值是另一个 expression
`${parseInt(100 * task.progress)}`%
这里我们看到了 template literals 的使用, vanilla javascript 的一个特性。
Template literals are enclosed by the backtick (` `)
Template literals can contain placeholders
[Placeholders] are indicated by the dollar sign and curly braces (${expression})
当 javascript 看到这个语法时,expression
被计算,这是我们发现第一个语法错误的地方
//In
`${parseInt(100 * task.progress)}`%
//The expression is "parseInt(100 * task.progress)"
//simplifying we get
`${expression}`%
//and we know that `${expression}` is a string
现在可能更容易看出
"string"%
没有语法意义。
解决方案?将 %
放在 template literal
`${parseInt(100 * task.progress)}%`
足够简单
向上移动
{'width':`${parseInt(100 * task.progress)}`% ;}
可以改成
{'width':`${parseInt(100 * task.progress)}%` ;}
但是 ;
不属于 object
。例如,{'attr':'1';}
无效。这给我们留下了
{'width':`${parseInt(100 * task.progress)}%`}
鳍
作为对读者的挑战,这等同于
:style="{'width':parseInt(100 * task.progress)}+'%'}"
提供的链接应该足以帮助理解。
TLDR:你有一个语法错误; :style="{'width':`${parseInt(100 * task.progress)}%`}"
有效
关于javascript - Vue.js 动态 <style> + 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61027269/