Search code examples
vuejs2vue-cli

How to access data from outside the instance in Vue js?


I'd like to get access to vm data from outside the instance like so:

myComponent.vue

export default {
    data() {
        return {
            name: 'Joe'
        };
    }
}

main.js

var vm = new Vue({
    el: '#app',
    render: h => h(myComponent)
});

Desired Result

console.log(vm.name);   // should return - Joe

For some reason, console returns undefined. What I'm doing wrong?


Solution

  • To access vue.js object datas from inside you can use $property_name. Example

    var vm = new Vue({
        el: '#app',
        data() {
          return {
            name: "Kapucni",
          }
        },
      template: '<div>{{ name }}</div>'
    });
    
    // use $name .property
    console.log(vm.$data.name);
    console.log(vm.$el);
    // calling functions from $method, etc ...
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
    
    <div id='app'>
      
    </div>