【发布时间】:2023-03-19 17:00:04
【问题描述】:
我正在尝试使用 vue 组件为跨度数组随机生成样式。我正在拆分消息并使用 v-for 显示单独的跨度,每个跨度都有自己的单词。
const textFx = Vue.component('text-fx', {
template: '<div class="textFx"><span v-bind:style="{opacity: Math.random().toFixed(2)}" v-for="words in wordArray">{{words}}</span></div>',
props:['message'],
data: function() {
return {
wordArray: []
}
},
methods: {
setMessage: function() {
this.wordArray = this.parseMessage;
},
},
computed: {
parseMessage: function() {
var temp = this.message.split(" ");
for(var i = 0; i < temp.length - 1; i++) {
temp[i] += " ";
}
return temp;
},
},
created: function() {
this.setMessage();
}
});
如您所见,我正在随机设置每个跨度的不透明度。在该示例中,它按预期工作,但我不想像这样对每个随机属性进行硬编码,当然,我更喜欢使用方法或计算属性。这是我尝试添加到组件中的内容:
computedStyle: function() {
var o = Math.random().toFixed(2);
return {
'opacity': o,
};
}
并像这样将其添加到跨度中:
'<div class="textFx"><span v-bind:style="computedStyle" v-for="words in wordArray">{{words}}</span></div>',
这在技术上确实有效,它提供了一个随机的不透明度值,但它将相同的随机值应用于所有跨度,而不是像硬编码示例那样单独应用。
我如何构造它以允许方法或计算属性重新计算所呈现的每个跨度的 Math.random 值?
【问题讨论】:
标签: javascript css random vue.js components