Home > OS >  Vue.js setup() and mounted()
Vue.js setup() and mounted()

Time:03-27

I am fairly new to Vue.js and am currently working on a project. I currently have some constants declared in setup(), lets call one of the constant "c", and I want to get them from within mounted(). I realized that I can still console.log(this.c) within mounted() to get the constant printed out but when I try to console.log(this.c) within a function in mounted() I can no longer get it and I get an error Uncaught (in promise) TypeError: Cannot read properties of undefined.

Why is this so? And what work arounds are there?

Example:

    setup() {
       const c = ref(1)
    },

    mounted() {
       console.log(this.c) // prints 1 on console
       
       function doesSomething() {
          console.log(this.c) // TypeError: Cannot read properties of undefined
          ...
       }
    }

CodePudding user response:

mounted is an option in the options api which is different than the composition api using the setup hook, you could use onMounted hook in setup to replace mounted option:

import {onMounted} from 'vue';

setup(){
 let c='some content'

 onMounted(()=>{
    console.log(c)// don't use this keyword
  })

}

CodePudding user response:

The function doSomething in the mounted hook should be declared with an arrow function instead, since function declaration has its own this binding:

mounted() {
  console.log(this.c)

  const doesSomething = () => {
    console.log(this.c) // Ok
  }
}
  • Related