Petite-vue Init attribute in HTML script tag

Viewed 645

I recently saw this Vue.js snippet by Evan You on Twitter, and I don't understand what the init attribute in the script tag does. I could not find anything about this on MDN or similar sites.

The defer attribute is clear to me.

<script src="https://unpkg.com/petite-vue" defer init></script>

<!-- anywhere on the page -->
<div v-scope="{ count: 0 }">
  {{ count }}
  <button @click="count++">inc</button>
</div>
3 Answers

It's explained in the repo Readme file in the Usage section :

The init attribute tells petite-vue to automatically query and initialize all elements that have v-scope on the page.

and according to this code snippet it's a custom attribute and it's used to mount the app if the script tag is present :

let s
if ((s = document.currentScript) && s.hasAttribute('init')) {
  createApp().mount()
}

As @Boussadjra Brahim mentioned, init is a custom attribute used to mount the app in petite-vue.

In addition to the point, If you don't want the auto init, remove the init attribute and move the scripts to end of <body>

<script src="https://unpkg.com/petite-vue"></script>
<script>
  PetiteVue.createApp().mount()
</script>

Or, use the ES module build:

<script type="module">
  import { createApp } from 'https://unpkg.com/petite-vue?module'
  createApp().mount()
</script>

For More Info Refer : Docs

The init attribute according to the README file on the petite-vue repo instructs petite-vue that on the load of the page to immediately find and initialize all elements that have the v-scope as attributes on a that page.

However you can manually initialize petite-vue by omitting the init attribute and making sure the script tag you are initializing petite-vue in is at the end of the body tag <body> and then follow the docs on the initializing steps.

https://github.com/vuejs/petite-vue#manual-init

Related