You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue项目调用moveImage函数报错“this.moveImage is not a function”求解决

解决Vue中this.moveImage is not a function报错问题

嘿,我来帮你搞定这个问题!你遇到的报错其实是两个小错误导致的,咱们一步步拆解:

问题根源

  1. 错误的方法存放位置:你把moveImage放在了computed里,但computed是计算属性,用来基于响应式数据计算出一个新的返回值,它不是用来定义可调用方法的地方——这直接导致this.moveImage不是一个可执行的函数。
  2. setInterval调用姿势错了:你写的setInterval(this.moveImage(), this.changeInterval)会立即执行moveImage,并把它的返回值(这里是undefined)传给定时器,而不是传递函数本身的引用,定时器自然识别不了这是个可执行的函数。

修复方案

只需要做这几个调整:

  • 把moveImage移到methods选项中,这才是组件方法该待的地方;
  • 修改setInterval的调用方式,传递函数引用(不要加括号);
  • 额外加一步:在组件销毁时清除定时器,避免内存泄漏。

修正后的完整代码

<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,
      timer: null // 存储定时器ID,用于后续清除
    };
  },
  created() {
    // 传递方法引用,不要加括号!
    this.timer = setInterval(this.moveImage, this.changeInterval);
  },
  beforeUnmount() {
    // 组件销毁前清除定时器,防止内存泄漏
    clearInterval(this.timer);
  },
  methods: {
    moveImage() {
      this.imgTop = Math.round(Math.random() * (screen.height - this.imgHeight));
      this.imgLeft = Math.round(Math.random() * (screen.width - this.imgWidth));
    }
  }
};
</script>

额外小提示

  • methods是Vue组件专门用来定义可调用方法的选项,这里的方法会自动绑定组件实例的this,不用额外处理;
  • 记得清除定时器是个好习惯,不然组件销毁后定时器还在后台跑,会浪费浏览器资源哦。

内容的提问来源于stack exchange,提问作者German Varanytsya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:29:43