Home » vue » this.moveImage is not a function

this.moveImage is not a function

Posted by: admin November 26, 2021 Leave a comment

Questions:

i’m trying to use setInterval with my function moveImage which changes position of my image!
here is my code:

<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>

as you can see i am using vue.js and getting an error “this.moveImage is not a function”
help me please to solve that problem!

Answers:

That’s because moveImage is not a method is a computed property. As a computed property vue will generate a getter for it.

You need to move the definition to methods

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

And in the call to setTimeout you want the function that its return value, so you need to call it like this

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