Home > database >  A function that is defined inside the methods{} is showing an error when it is called outside
A function that is defined inside the methods{} is showing an error when it is called outside

Time:06-23

export default{
name: 'navigation',
components:{
    menuIcon,
},
data() {
    return {
        mobile: null,
        mobileNav: null,
        windowwidth: null,
    }
},
methods: {
    checkScreen() {
        this.windowwidth = window.innerWidth;
        if(this.windowwidth <= 750) {
            this.mobile = true;
            return;
        }
        this.mobile = false;
        this.mobileNav = false;
        return;
    },
    toggleMobileNav() {
        this.mobileNav = !this.mobileNav;
    },
},
created() {
    window.addEventListener("resize",checkScreen);
    this.checkScreen();
},
};

In this I have used the checkScreen() function inside the created() tab and then when i saved my program, the compiler showed error that checkScreen is not defined and then it points to the line where I used checkScreen in created(). Can somebody clarify on why this is happening. enter image description here

CodePudding user response:

You simply forgot the this keyword in the listener callback.

created() {
    window.addEventListener("resize", this.checkScreen);
    this.checkScreen();
}

The this keyword within Vue gives you easy access to all your data and functionality. Whether you want to access a data property, computed property, prop component, or function, you can find them all directly on the this keyword.

  • Related