[Vuejs]-Fetch data from MySQL database in Nuxt.js 3

1👍

First of all, since you use Nuxt 3, not 2, you want to use the way a plugin is done in Nuxt 3.

Documentation for this

You probably want to have something like this:

import mysql from 'mysql'

export default defineNuxtPlugin(() => {

  const connection = mysql.createConnection({
      host: 'myhost',
      user: 'myusername',
      password: 'mypassword',
      database: 'mydatabase',
  })
  connection.connect()

  return {
    provide: {
      mysql: connection
    }
  }
})

Documentation for the above code

Additionally, you want to use Nuxt 3 in your components, just like this:

<script setup lang="ts">
const { $mysql } = useNuxtApp()

</script>

Leave a comment