javascriptvue.jsvuejs2vuejs3

Vue.js 3 - instance without a component?


In Vue.js 2, it's possible to create a reactive instance without a component, like this:

var vue = new Vue({
    el: '#root',
    data: { /*... */ },
    methods: { /* ... */ }
})

In fact, this is the basic usage pattern that Vue.js 2 documentation starts with.

I think it's a very elegant way of adding reactivity to an existing DOM element, and the created instance is easy to manipulate programmatically. Is there an equivalent in Vue.js 3?


Solution

  • Use CDN

    // CDN Vue Import
    const { createApp, ref } = Vue
    
    const app = createApp({
      setup() {
        const msg = ref("hello world")
        
        return { msg }
      },
    }).mount('#app')
    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
    
    <div id="app">
       <div>{{ msg }}</div>
       <input v-model="msg" />
    </div>

    Use CDN (with template)

    // CDN Vue Import
    const { createApp, ref } = Vue
    
    const app = createApp({
      setup() {
        const msg = ref("hello world")
    
        return { msg }
      },
      template: `
        <div>{{ msg }}</div>
        <input v-model="msg" />
      `
    }).mount('#app')
    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
    
    <div id="app"></div>

    Use CLI

    Steps

    1. Install packages by npm
    2. Create your app
    3. Make "production" code (skip if it's need same project)
    4. Use your vue app (implement another project or use in same project)

    Example

    import { createApp, ref } from 'vue'
    
    const app = createApp({
      setup() {
        const msg = ref("hello world")
    
        return { msg }
      },
      template: `
        <div>{{ msg }}</div>
        <input v-model="msg" />
      `
    }).mount('#app')
    
    <div id="app"></div>
    

    More information

    In-DOM Root Component Template - Vue.js Docs

    Multiple application instances - Vue.js Docs