【问题标题】:VueJS random number gets generated only onceVueJS 随机数只生成一次
【发布时间】:2017-09-10 21:39:34
【问题描述】:

我想制作一个简单的 VueJS 应用程序,它能够使用多个 API、抓取图像并将其显示给用户。这是我在看了一些课程视频后第一次尝试使用Vue,所以如果我不使用VueJS函数而是使用纯JS,请不要讨厌我。

我希望用户单击一个按钮,然后它将从 API 请求图像。有效的是它随机选择一个 api,但对于 Flickr API,我需要指定一个标签(保存在一个数组中,也随机选择)。但它只选择一次标签,每次我再次调用该函数时它都是同一个标签!表示该函数仅在页面重新加载后才会执行。

为什么会这样,我该如何解决? 提前致谢。

到目前为止我的代码

var vm = new Vue({
    el: '#app',
    data() {
        return {
            // some data
            apis: [this.flickr(), this.desktopper()],
            wallpaper: '',
            wallpapers: [],
            screenWidth: window.screen.width,
            screenHeight: window.screen.height,
        }
    },
    methods: {
        // The random function
        randomNumber(min, max) {
            return Math.floor(Math.random() * (max - min) + min);
        },
        // The main function, calls an api and should get the image source
        requestWallpaper() {
            var wallpaper = this.apis[ this.randomNumber(0, this.apis.length) ];
            console.log(wallpaper);
        },
        // Flickr API request random image
        flickr() {
            // Most popular tags of all time on Flickr (tags are needed to request images)...
            var popularTags = ['sunset','beach','water','sky','red','flower','nature','blue','night','white','tree','green','flowers','portrait','art','light','snow','dog','sun','clouds','cat','park','winter','landscape','street','summer','sea','city','trees','yellow','lake','christmas','people','bridge','family','bird','river','pink','house','car','food','bw','old','macro','music','new','moon','orange','garden','blackandwhite'];
            // Grab a random tag
            var tag = popularTags[ this.randomNumber(0, popularTags.length) ];
            return tag;
        },
        // Desktopper.co API request random image
        desktopper() {
            return 'desktoppr';
        }
    }
});

HTML

<body>
<div id="app">
    <div>
        <div>
            <img id="random" src="" />
        </div>
        <div>
            <button v-on:click="requestWallpaper">New Wallpaper</button>
        </div>
    </div>
</div>
</body>

【问题讨论】:

  • 请包含您调用requestWallpaper() 方法的HTML。
  • 抱歉错过了!我已经包含了 body 部分,head 中只有用于重置 body 和 unpkg cdn vue 文件的内联 css。

标签: javascript vue.js


【解决方案1】:

问题是你是apis 数组。

apis: [this.flickr(), this.desktopper()],

您同时调用了flickr()desktopper() 方法。这就是括号 () 的含义,它们是为了让您可以将参数传递给该方法。相反,您应该排除括号,以便您只为每个方法存储一个引用

apis: [this.flickr, this.desktopper],

然后,当您调用 requestWallpaper() 时,您需要先获取随机 API,然后然后从其引用中调用它。

// get a reference to a random API
var api = this.apis[ this.randomNumber(0, this.apis.length) ];
// call that reference, with parenthesis and get the wallpaper result
var wallpaper = api()

【讨论】:

  • 很好的解释,非常感谢!已批准。
猜你喜欢
  • 2023-01-03
  • 2019-05-04
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多