【问题标题】:v-bind behavior with Math.random not as expected与 Math.random 的 v-bind 行为不符合预期
【发布时间】: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


    【解决方案1】:

    计算属性只有在其任何依赖数据属性发生更改时才会更新其值。由于您的 computedStyle 没有依赖属性,因此计算它的函数只运行一次。该计算值不会因后续引用而改变。

    您的情况是您希望定义一个返回样式对象而不是使用计算属性的方法:

    methods: {
      getComputedStyle() {
        return { opacity: Math.random().toFixed(2) };
      }
    }
    

    然后,在绑定到样式时调用该方法,如下所示:

    <span v-bind:style="getComputedStyle()"></span>
    

    Here's a working codepen.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 2017-01-27
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多