Vuex is a very useful state management scheme, but sometimes the project is not large enough to require many actions and mutations, but it does need to share some data and state between components, so a small state sharing library, VUE-Stores, was written

link

GitHub: vue-stores

Demo: vue-stores-demo

NPM: vue-stores

instructions

Vue-stores are small, with only 50 lines of code, but they don’t allow time-travel in dev-Tools like vuex does

The principle of

The status and methods that need to be shared globally in the Root component are taken out and added as computing attributes in the sub-component, and the change of data is hijacked by get set to ensure that the values modified and obtained in the sub-component are from the Root component.

usage

I’m just going to take the code from the demo

The root component defines shared data

import stores from 'vue-stores'
Vue.use(stores)

new Vue({
  ...
  data: {
    state: {
      showModal: false,
      global: {
        txt: 'shared Text'
      }
    }
  },
  methods: {
    toast(){
      alert('this is a shared method')
    }
  }
})Copy the code

State is a custom property, and objects in data.state are state data that can be shared among components

Child components use shared data

To use shared data in a component app, you can use aliases such as Modal and Alert

stores: {
  txt: 'state.global.txt',
  modal: 'state.showModal',
  alert(){
    return 'toast'
  }
}Copy the code

Custom attribute stores are also used here, where TXT modal alert is converted to the calculation attribute of this component

Similarly, shared data is referenced in the same way in other child components, depending on the source code

Top

Bottom

Modal

Bottom’s child component, Other

The show attribute value in the Modal component can be changed not only inside the component by the close button, but also in the external app component by the toggle method, but their state is always synchronized, because they both refer to the state-showmodal of the root component

The alias method alert defined in the component app actually refers to the toast method in the component. Calling alert means calling toast

The last

Vue-stores is just another idea of state management, which is also a kind of state management mode based on business driving and other schemes of the community. It is suitable for state sharing scheme in small projects. For long-term large projects, Vuex is still recommended, after all, the whole family bucket, after all, the son….


Did this article help you? Welcome to join the front End learning Group wechat group: