2

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

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
user15558176
  • 61
  • 1
  • 4
  • It's impossible for this code to work. this.c won't be available without `c` to be returned from setup. It's unclear what's the purpose of doesSomething. Usually a function is a method in components. – Estus Flask Mar 27 '22 at 06:55
  • Possible duplicate of https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Estus Flask Mar 27 '22 at 06:55

2 Answers2

4

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
  }
}
Ernest
  • 174
  • 7
1

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

}
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • 1
    @user15558176 It's possible but not a good practice. setup is supposed to fully replace options api, so the latter can be considered legacy. – Estus Flask Mar 27 '22 at 06:51