Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between declaring variables in Vue?

Could you explain the difference between declaring variables in different ways. When I should use these ways of declaring?

<script>
const someVariable = 12345

export default {
  name: 'App',
}
</script>
<script>

export default {
  name: 'App',
  data() {
    return {
      someVariable: 12345
    }
  }
}
</script>
like image 889
Daniil Shelest Avatar asked Mar 02 '23 11:03

Daniil Shelest


1 Answers

In the first one, you can't use the someVariable in your template

<script>
const someVariable = 12345

export default {
  name: 'App',
}
</script>
<template> <p> {{someVariable}} </p> </template> //doesn't work

Available in Vue3:

to make it work you can add a setup keyword in your script but you have to wrap your variable value with ref(...) or reactive(...) if you want to make it reactive to changes More info

<script setup>
const someVariable = 12345

export default {
  name: 'App',
}
</script>
<template> <p> {{someVariable}} </p> </template> //works (you can see the data)
like image 170
Sinan Yaman Avatar answered Apr 30 '23 07:04

Sinan Yaman