javascript - this.moveImage 不是一个函数

标签 javascript function vue.js ecmascript-6 setinterval

我正在尝试将 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 不是函数” 请帮我解决这个问题!

最佳答案

这是因为 moveImage 不是一个方法,而是一个计算属性。作为计算属性,vue 将为它生成一个 getter。

您需要将定义移至方法

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);
}

关于javascript - this.moveImage 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55240632/

相关文章:

arrays - 如何在 Kotlin 中定义 funs(函数)数组?

javascript - Vue Js - 单击触发方法时从表中删除 TR 祖父节点

javascript - 如何在Vue JS中按下父组件上的按钮时刷新子组件的方法?

javascript - 连接调试器时 Electron BrowserWindow 无法获得响应

javascript - NodeJS - 为什么串行读取器失败?

javascript - 这个 JS 函数如何在不调用数组的情况下从数组中提取项目?

javascript - angular-ui:轮播上的触发事件

c# - VS2013 C# 函数声明 => 符号

javascript - 如何仅在一个国家和操作系统中运行 javascript 函数?

javascript - V-model 未绑定(bind)在 DOM 元素中