30

I have a fairly simple VueJS app, 3 components (Login, SelectSomething, DoStuff)

Login component is just a form for user and pass input while the second component needs to display some data obtained in the login progress.

How can I share data from one component to the others? So that when I route to second component I still have the data obtained in the Login one?

5
  • 5
    Have you read the section in the Vue guid on state management? Commented Oct 24, 2016 at 17:46
  • Not yet, but it looks like what I need. Guess that is what happens when you are to eager to start developing before finishing to read the whole documentation.
    – daniels
    Commented Oct 24, 2016 at 17:58
  • Hi there! If you found my answer accurate (and helpful), please accept it
    – Dan Mindru
    Commented Nov 1, 2016 at 22:38
  • 2
    @PatrickSteele 's answer is what I was looking for but he added it as a comment which I can't "accept". With your answer I can only pass data to child components and not sibling components. Right? Or am I missing something?
    – daniels
    Commented Nov 2, 2016 at 12:18
  • Possible duplicate of How can I share data between non parent-child components in Vue Commented Feb 8, 2017 at 18:04

3 Answers 3

23

You can either use props or an event bus, where you'll be able to emit an event from a component and listen on another

vm.$on('test', function (msg) {
  console.log(msg)
})

vm.$emit('test', 'hi')
// -> "hi"
13

In Vue.js components can communicate with each other using props or events. It all depends on the relation between your components.

Let's take this small example:

<template>
<h2>Parent Component</h2>
<child-component></child-component>
</template>

To send information from the parent to Child, you will need to use props:

<template>
<h2>Parent Component</h2>
<child-component :propsName="example"></child-component>
</template>

<script>
export default {
 data(){
  return{
   example: 'Send this variable to the child'
  }
 }
}
</script>

To send information from the child to the parent, you will need to use events:

Child Component

<script>
 ...
 this.$emit('example', this.variable);
</script>

Parent Component

<template>
<h2>Parent Component</h2>
<child-component @example="methodName"></child-component>
</template>

<script>
export default {
 methods: {
  methodName(variable){
   ...
  }
 }
}
</script>

Check the documentation of vue.js for more information about this subject. This is a very brief introduction.

4

Use this small plugin if you have a lot of nested components:

Vue.use(VueGlobalVariable, {
  globals: {
    user: new User('user1'),
    obj:{},
    config:Config,
    ....
  },
});

Now you can use $user in any component without using props or other

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.