[Vuejs]-In VueJs3 why can't I access data properties from the vue object? (it worked in Vue2)

4πŸ‘

βœ…

In Vue 2, new Vue() returns the root component.

In Vue 3, createApp() returns the application instance, and the root component is returned from the application instance’s mount():

var app = Vue.createApp({
  data() {
    return {
      count: 101,
    }
  }
})
     πŸ‘‡
var root = app.mount('#appTemplate')
console.log(root.count) // => 101
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <script src="https://cdn.jsdelivr.net/npm/vue@3.0.5/dist/vue.global.js"></script>
</head>
<body>
    <h1>Vue3 app.variable example</h1>

    <!-- vue template -->
    <div id="appTemplate">
        <div style="margin-bottom:20px">Count: <span v-text="count"></span></div>
        <button v-on:click="increment()">Increment</button>
    </div>

    <script type="text/javascript">
        //Vue3 OptionsAPI 
        var app = Vue.createApp({
                data: function() {
                    return {
                        count: 101
                    }
                },
                methods: {
                    increment: function() {
                        this.count++;
                    }
                },
                created: function(){
                    _app = this;
                }
            }
            
        );
        var root = app.mount("#appTemplate");

        alert("root.count is:" + root.count);


    </script>
</body>
</html>

Alternatively, you could chain the mount() call off of createApp():

var app = Vue.createApp().mount('#appTemplate')
console.log(app.count) // => 101
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <script src="https://cdn.jsdelivr.net/npm/vue@3.0.5/dist/vue.global.js"></script>
</head>
<body>
    <h1>Vue3 app.variable example</h1>

    <!-- vue template -->
    <div id="appTemplate">
        <div style="margin-bottom:20px">Count: <span v-text="count"></span></div>
        <button v-on:click="increment()">Increment</button>
    </div>

    <script type="text/javascript">
        //Vue3 OptionsAPI 
        var app = Vue.createApp({
                data: function() {
                    return {
                        count: 101
                    }
                },
                methods: {
                    increment: function() {
                        this.count++;
                    }
                },
                created: function(){
                    _app = this;
                }
            }
            
        ).mount("#appTemplate");

        alert("app.count is:" + app.count);


    </script>
</body>
</html>
πŸ‘€tony19

1πŸ‘

You could also access that property before mounting the app :

 app._component.data().count

Leave a comment