user3118789
user3118789

Reputation: 609

Vue.js Get data from another component

I have 2 components: A and B.

Component A:

import B from '../components/B.vue';

export default {

    components: {
        B
    },

    methods: {
        test: function() {
            console.log(B.data().settings);
        }
    }
}

And component B:

export default {

    data() {
        return {
            setting: '123'
        }
    }

}

When I trigger test method then I get the value is 123. But when I enter new value from an input and trigger test method again I can't get the new value, the value is still 123.

I have no idea about this. Thank you so much !!!.

Upvotes: 2

Views: 4876

Answers (1)

Yerko Palma
Yerko Palma

Reputation: 12339

You are executing the data function of the component definition. To get the value you want, from the instance of a component, just call the data you want. For example:

import B from '../components/B.vue';

// as I say, work on instance of Vue, not in components definitions 
let b = new B()

console.log(b.settings) // logs the settings for that instance, this value is reactive
console.log(b.$data) // log all the current data for that component, also reactive
console.log(B.data()) // log the definition data, not reactive

Now you must resolve how to get a reference to the B instance from the A Vue instance, as there could be more than one B component in A

Upvotes: 3

Related Questions