2

I have two components: component A and component B. A.vue is like:

export default {
    name: 'A',
    data () {
        var: true
    }
}

B.vue is:

import A from './A'
export default {
    name: 'B',
    components: {
        A
    }
}

I want to use the dynamic value of variable var of component A in component B. I set a watcher therefore:

import A from './A'
export default {
    name: 'B',
    watch: {
        A.data().var: func () {
            console.log('Value of var changed in A.')
        }
    }
    components: {
        A
    }
}

However, this approach does not work. Components A and B does not have the child-parent relationship, and therefore, I cannot use props. How can I do this?

2 Answers 2

1

Assuming that both instances of A and B live within the same root instance, you could use that root as an event hub for the communication between the 2 components.

Step 1 | The the root template that calls handleAVarChange when needed:

const rootTemplate = `
    <div class="root">
        <A @var-change="handleAVarChange"></A>
        <B v-bind:AVar="AVar"></B>
    </div>
`;

Step 2 | the Vue root script that implements rootTemplate:

const root = new Vue({
    template: rootTemplate,
    data() {
        return { AVar: null };
    },
    methods: {

        handleAVarChange(value) {
            this.AVar = value;
        }
    }
});
  • template: The template that both includes A and B
  • data returns an object with property AVar, which we'll use to store the source variable on A.
  • methods.handleAVarChange is available as event handler within root.template.

Step 3 | $emit an event named 'var-change' with the new value from A:

export default {
    name: 'A',
    data () {
        return {
            Var: true,
        }
    },

    methods: {
        onSomeEvent(varValue) {
            this.$emit('var-change', varValue);
            // or maybe...
            this.$emit('var-change', this.Var);
        },
    },
}

Step 4 | Make sure that AVar is set as prop within B:

export default {
    name: 'B',
    props: ['AVar'],
    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I had resorted exactly to this approach after posting this question.
1

I would consider using a simple state management (Vue docs) for your problem.

var store = {
  debug: false,
  state: {
      myVar: false
  },
  setMyVarAction (value) {
    this.state.myVar = value
  }
}

And assign the store to your components A and B:

data () {
  return  {
    sharedStore: store.state
  }
}

jsfriddle with a working example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.