【问题标题】:I want to get a random v-for template without be the same我想得到一个不一样的随机 v-for 模板
【发布时间】:2020-06-24 19:17:07
【问题描述】:

我想在 v-for 循环中获取一个随机值来制作文章幻灯片。 我想将我的 randomGen 计算函数替换为随机后生成器,而不是两倍。 完整的应用程序:https://jsfiddle.net/z7sfm5tq/ 我已经这样做了:

<div class="article-ran">
  <div class="bloc" v-for="post in randomGen">
    <img v-bind:src="post.img"/>
    <span>{{ post.cat }}</span>
    <p v-bind:href="post.link" target="_blank">
    {{ post.title }}
    </p>
</div>

还有我的 vuejs 应用


computed: {
  randomGen(){
    Math.floor(Math.random() * this.postList.length);
    this.pickerList = this.postList;
    //so this is the randomGen function that's not working
  }
}
})

【问题讨论】:

  • 我不明白你的问题是什么?
  • A.放入一个方法,而不是计算 B。如果您不想要相同的值,那么您需要保存它们并检查保存的值。
  • 如何通过 id 保存值?

标签: vue.js vuejs2


【解决方案1】:

好的,我自己修复了代码,即使它是一个计算函数,受此模板的启发:Vue.js proper random ordering of v-for loop

computed: {
    randomList(){
        var currentIndex = this.postList.length;
        var temporaryValue;
        var randomIndex;
        var myRandomizedList;

        // Clone the original array into myRandomizedList (shallow copy of array)
        myRandomizedList = this.postList.slice(0)

        // Randomize elements within the myRandomizedList - the shallow copy of original array
        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = myRandomizedList[currentIndex];
            myRandomizedList[currentIndex] = myRandomizedList[randomIndex];
            myRandomizedList[randomIndex] = temporaryValue;
        }

        // Return the new array that has been randomized
        return myRandomizedList;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-24
    • 2016-10-16
    • 2013-11-24
    • 2015-11-25
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多