Armand
Armand

Reputation: 2827

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?

Upvotes: 9

Views: 20126

Answers (4)

Sara
Sara

Reputation: 509

I had a similar problem and I was able to access the data using vm._data.name

Upvotes: 0

Best practices are using State in Vuex for unified data storage and secure and standardized data modification and retrieval. You can read more here: https://v3.vuex.vuejs.org/#what-is-a-state-management-pattern.

If you using State in Vuex and Vue 3 you can:

store.js

import 'es6-promise/auto';
import {createStore} from 'vuex'

export const store = createStore({
    state () {
        return {
            count: 1,
        }
    },
    mutations: {
        incrementCount (state) {
            state.count++
        },
        setCount (state, newValue) {
            state.count = newValue;
        },
    },
    getters: {
        getCount: state => {
            return '*' + state.count + '*';
        }
    }
})

app.js

import {store} from "./store"; 
const app = createApp({...})
app.use(store);
export const vue_app = app.mount('#vue_app');

and in Javascript to modify:

const store = vue_app.__vue_app__._context.provides.store; // Store instance
store._state.data.count; // get value
store.getters.getCount; // get value by the getter
store._mutations.incrementCount[0](); // modification by the mutation "incrementCount"
store._mutations.setCount[0](123); // modification by the mutation "setCount"
store._state.data.count = 123; // direct modification

Upvotes: 0

Armand
Armand

Reputation: 2827

Thanks to comments from ittus, I realised that I have to look for child components, not the root component.

We can get to child component like so:

vm.$children[0].name

where $children[0] is a direct (and first in this case) child of the root component.

Upvotes: 2

Sabee
Sabee

Reputation: 1811

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/[email protected]/dist/vue.js"></script>

<div id='app'>
  
</div>

Upvotes: 9

Related Questions