• Creating a Store without Vuex in vue.js 2.6

  • Alex Jover

  • Translator: Uncle Ho, the programmer

Special disclaimer: This article is a series posted by author Alex Jover on VueDose.

Copyright belongs to the author.

The translator had already communicated with the author before the translation to get permission to translate the whole series.

In order not to disturb your reading, the authorization record is placed at the end of this article.

Vue.js 2.6 introduces some new features, and one of my favorites is the global API vue.Observable

Now you can create reactive objects outside the scope of the component. And when you use them in a component, it triggers the corresponding render update when it changes.

Based on this, you can create a simple store without vuEX, which is ideal for simple scenarios where only external state needs to be shared across components.

For example, let’s now create a simple calculator to expose state to our store. Create the store.js file first:

import Vue from "vue";

export const store = Vue.observable({
  count: 0
});
Copy the code

If you’re familiar with and like the ideas behind mutations and Actions, you can also create a simple function that updates your data:

import Vue from "vue";

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

export constmutations = { setCount(count) { store.count = count; }};Copy the code

Now you just need to use it in the component, just like Vuex to get state, which we’ll use to calculate the properties and call the Mutations instance method.

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="setCount(count + 1);">+ 1</button>
    <button @click="setCount(count - 1);">- 1</button>
  </div>
</template>

<script>
  import { store, mutations } from "./store";

  export default {
    computed: {
      count() {
        returnstore.count; }},methods: {
      setCount: mutations.setCount
    }
  };
</script>
Copy the code

If you want to try this example out for yourself, I’ve compiled it for you on CodeSandbox, go check it out!

You can read the article online and copy and paste the source code. If you like this series, please share it with your colleagues!

conclusion

Other articles in this series will be translated and posted to nuggets as they are published on the series website. Please keep an eye on uncle He, I believe I will bring you more quality content, don’t forget to like ~

If you want to know more about the translator, please check out the following:

  • Personal blog: blog.hadesz.com
  • Personal Github repository: github.com/hadeshe93
  • Personal wechat official account: Search “Uncle He”

Request translation of authorization records




If you think this article is good, share it with your friends