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:
- I would have a input on the page that sends a number to the backend,
- which in turn responds with a an incremented number
- which is concurrently displayed on the main page.
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:
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.