this.moveImage不是一个函数

问题描述 投票:0回答:1

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

javascript function vue.js ecmascript-6 setinterval
1个回答
2
投票

这是因为moveImage不是一种方法是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);
}
© www.soinside.com 2019 - 2024. All rights reserved.