Home > front end >  How to use Compose API in a standalone (one-file) Vue3 SPA?
How to use Compose API in a standalone (one-file) Vue3 SPA?

Time:02-03

I write (amateur) Vue3 applications by bootstrapping the content of the project and then building it for deployment(*). It works great.

I need to create a standalone, single HTML page that can be loaded directly in a browser. I used to do that when I was starting with Vue a few years ago (it was during the transition v1 → v2) and at that time I immediately found the proper documentation.

I cannot find a similar one for Vue3 and the Composition API.

What would be a skeleton page that would display the value reactive variable {{hello}} (that I would define in <script setup> in the context of a full, built application)

This is how I used to do it in the past (I hope I got it right)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://unpkg.com/vue@2"></script>
</head>
<body>

<div id="app">
    {{hello}}
</div>

<script>
    // this is how I used to do it in Vue2 if I remember correctly
    new Vue({
        el: '#app',
        data: {
            hello: "bonjour!"
        }
        // methods, watch, computed, mounted, ...
    })
</script>

</body>
</html>

(*) I actually use the Quasar framework but this does not change the core of my question.

CodePudding user response:

You couldn't use script setup using the CDN, according to official docs:

<script setup> is a compile-time syntactic sugar for using Composition API inside Single File Components (SFCs)

but you could use the setup hook inside the page script as follows :

const {
  createApp,
  ref
} = Vue;
const App = {
  setup() {
    const hello = ref('Bonjour')


    return {
      hello
    }

  }


}
const app = createApp(App)
app.mount('#app')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>

<div id="app">
  {{hello}}
</div>

  •  Tags:  
  • Related