首页 > 解决方案 > this.moveImage 不是函数

问题描述

我正在尝试将 setInterval 与我的函数 moveImage 一起使用,这会改变我的图像位置!这是我的代码:

<template>
  <div class="randImg">
    <img v-bind:style="{top: imgTop + 'px', left: imgLeft + 'px',height: imgHeight + 'px', width: imgWidth + 'px'}"
         class="image" v-bind:src="vue">
  </div>
</template>

<script>
  const vue = require("../assets/images/vue.png");
  export default {
    name: "randImg",
    data() {
      return {
        vue,
        imgTop: 0,
        imgLeft: 0,
        imgHeight: 64,
        imgWidth: 64,
        changeInterval: 1000
      }
    },
    created() {
      setInterval(this.moveImage(), this.changeInterval);
    },
    computed: {
      moveImage() {
        this.imgTop = Math.round(Math.random() * (screen.height - this.imgHeight));
        this.imgLeft = Math.round(Math.random() * (screen.width - this.imgWidth));
      }
    }
  }
</script>

如您所见,我正在使用 vue.js 并收到错误“this.moveImage 不是函数”,请帮助我解决该问题!

标签: javascriptfunctionvue.jsecmascript-6setinterval

解决方案


那是因为moveImageis not a method is a computed property. 作为一个计算属性,vue 会为它生成一个getter

您需要将定义移至methods

methods: {
 moveImage() {
    this.imgTop = Math.round(Math.random() * (screen.height - this.imgHeight));
    this.imgLeft = Math.round(Math.random() * (screen.width - this.imgWidth));
  }
}

而在调用setTimeout你想要它的返回值的函数,所以你需要这样调用它

created() {
  setInterval(this.moveImage, this.changeInterval);
}

推荐阅读