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

Vue中methods内定义函数在created调用时提示未定义报错

报错原因

Vue组件methods里定义的方法,全部挂载在组件实例对象上,不会变成created钩子局部作用域里可直接访问的变量。你写window.addEventListener("resize",checkScreen)的时候,JS引擎会在当前作用域、全局作用域找名叫checkScreen的变量,找不到就直接抛未定义错误。
要访问组件实例上的方法,必须加this.前缀,也就是this.checkScreen。

额外注意的坑

直接传this.checkScreen给addEventListener也不对。原生DOM事件触发时,处理函数内部的this会指向绑定事件的元素(这里是window对象),到时候函数里写的this.windowwidth、this.mobile全是往window对象上挂属性,根本改不到Vue的响应式数据,逻辑完全失效。
另外如果不提前保存事件处理函数的引用,组件销毁时没法移除监听,会造成内存泄漏。

修正后的完整代码
export default{
    name: 'navigation',
    components:{
        menuIcon,
    },
    data() {
        return {
            mobile: null,
            mobileNav: null,
            windowwidth: null,
            resizeHandler: null
        }
    },
    methods: {
        checkScreen() {
            this.windowwidth = window.innerWidth;
            if(this.windowwidth <= 750) {
                this.mobile = true;
                return;
            }
            this.mobile = false;
            this.mobileNav = false;
        },
        toggleMobileNav() {
            this.mobileNav = !this.mobileNav;
        },
    },
    created() {
        // 用箭头函数固定this指向为组件实例,保存引用方便后续销毁
        this.resizeHandler = () => this.checkScreen();
        window.addEventListener("resize", this.resizeHandler);
        this.checkScreen();
    },
    // Vue2 请把生命周期名换成 beforeDestroy
    beforeUnmount() {
        window.removeEventListener("resize", this.resizeHandler);
    }
};

内容的提问来源于stack exchange,提问作者MAHEEDHAR A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 23:18:17