javascriptvue.jsnuxt.js

How Nuxt is diffrent from Vue when it comes to reactive variables?


I used Vue for years for my frontend (amateur) development and decided to give a try to Nuxt.

After going though the tutorial I thought I had a general idea and created a simple project where:

To this I created a new project in which I wrote a few files:

server/api/addOne.ts

export default defineEventHandler((event) => {
    const oldNumber = (getRouterParam(event, 'number') || 0) as number
    return {
        oldNumber: oldNumber,
        newNumber: oldNumber + 1,
    }
})

app.vue

<template>
  <div>
    <AddOne></AddOne>
  </div>
</template>

components/AddOne.vue

<template>
    <div>
        <input v-model="myNumber" />
        <button @click="sendToServer">send</button>
        <div> -{{ numberFromServer }}- </div>
    </div>
</template>

<script lang="ts">
const myNumber = ref(0)
const numberFromServer = ref(0)
const sendToServer = async (number: number) => {
    console.log('clicked')
    const { data, pending, error, refresh } = await useFetch('/api/addOne', {
        method: 'post',
        body: {
            number: myNumber.value
        }
    })
    numberFromServer.value = data.newNumber
    myNumber.value = -1
    console.log(`number from server: ${numberFromServer.value}`)
}
</script>

The app builds and displays what is expected:

enter image description here

The app does not work (inputting a number and pressing send doe nothing) and I get the following warnings:

 WARN  [Vue warn]: Property "myNumber" was accessed during render but is not defined on instance.
  at <AddOne>
  at <App>
  at <NuxtRoot>


 WARN  [Vue warn]: Property "numberFromServer" was accessed during render but is not defined on instance.
  at <AddOne>
  at <App>
  at <NuxtRoot>

I do not understand where they come from - myNumber and numberFromServer are defined in the component. I was already surprised that VSCode was not suggesting them when I was typing them but I thought that it was a matter of having the right plugin, maybe.

I think I am doing something fundamentally wrong,thus my question about where variables should be defined in Nuxt, versus where they are in Vue.


Solution

  • This isn't specific to Nuxt.

    The warning means exactly what it says, numberFromServer and myNumber are used in a template but aren't defined in a script. There should be return { myNumber, ... } for setup function, or const myNumber = ... for script setup syntax. This can also happen if setup failed to execute normally and threw an error, so the variables were defined but not returned.

    In this case there is no setup, this is is the first thing to check when such a warning occurs.

    It should be:

    <script setup lang="ts">