How to share data between components in VueJS

眉间皱痕 提交于 2019-12-02 17:33:03

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"

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!