4

I'm new to Vue.js 3, but I have a strange behavior accessing the “this” object in a component.

If my component is declared with the script setup, the access to “this” object is always undefined, see the below code:

<script setup>
  import { onMounted } from 'vue'

  onMounted(() => {
    console.info("Access KO: " + this)
  })
</script>

If I use the export default, everything works fine, see the below code:

<script>
export default {
  mounted() {
    console.info("Access OK: " + JSON.stringify(this) + "<<")
  }
}
</script>

Do you have any idea?

Thanks and regards. Giuseppe

3 Answers3

0

Arrow functions have a lexical this and its value within the arrow function is determined by the surrounding scope.In your case there is no surrounding scope.

that's the reason why we go with primitive functions.

Try the below code and see if this is working

<script setup>
  import { onMounted } from 'vue';
 
  onMounted() {
    console.info("Access KO: " + this)
  })
</script>

Note: There is nothing to do with export default. If you carefully observe, you are using primitive function in the second codeblock thatswhy its working.

Amaarockz
  • 4,348
  • 2
  • 9
  • 27
  • 1
    Hi AYK, Thanks for the feedback. I tried the solution you proposed, but also using the primitive function the "this" object is still undefined. Regards, Giuseppe – Giuseppe DS May 16 '22 at 06:13
  • There was a typ0, I have modified the solution, please check – Amaarockz May 16 '22 at 13:52
  • 1
    Hi AYK, thanks again for the suggestione, but nothing, it doesn't work, now I obtain "error Parsing error: Missing semicolon. (4:13)". Strange. – Giuseppe DS May 21 '22 at 15:13
  • doesn't work https://codesandbox.io/s/vue-3-composition-api-forked-jdumfv?file=/src/App.vue – Edito Jan 05 '23 at 07:38
0

Just found the solution here Add global variable in Vue.js 3

But basically, during setup, this is not available so if you have a variable you need there, you should provide it on the app creation and inject it wherever you need it

Camilo Casadiego
  • 907
  • 3
  • 9
  • 33
-1

onMounted uses callbacks, correct usage in this case should be like this

onMounted(    () =>  console.info("Access KO: " + this))
  • doens't work https://codesandbox.io/s/vue-3-composition-api-forked-pv6f36?file=/src/App.vue – Edito Jan 05 '23 at 07:37