Categories
Vue Answers

How to share data between components with Vue.js?

Spread the love

Sometimes, we want to share data between components with Vue.js.

In this article, we’ll look at how to share data between components with Vue.js.

How to share data between components with Vue.js?

To share data between components with Vue.js, we can use the Vue observable library.

For instance, we write

errors.js

import Vue from "vue";

export const errors = Vue.observable({ count: 0 });

to call Vue.observable with an object to create an observable state with the properties inside and export it.

Then we write

<script>
import { errors } from "./path/of/errors.js";
//...

export default {
  //...
  computed: {
    errors: {
      get() {
        return errors.count;
      },
      set(val) {
        errors.count = val;
      },
    },
  },
  //...
};
</script>

to add the errors computed property with a getter and setter.

In the get getter, we return the count value.

And in the set setter, we set the errors.count value to val.

This will be reflected in the components that uses errors.

Conclusion

To share data between components with Vue.js, we can use the Vue observable library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *