Skip to content
This repository has been archived by the owner on Dec 15, 2018. It is now read-only.
/ vuex-queries Public archive

Vuex-Queries helps you write query functions in Vuex

License

Notifications You must be signed in to change notification settings

whtsky/vuex-queries

Repository files navigation

Vuex-Queries

Build Status JavaScript Style Guide codecov NPM version FOSSA Status

Vuex-Queries helps you write query functions in Vuex

Usage

Write your queries in Vuex options:

const options = {
  state: {
    events: [{id: 1, author: ['a', 'b']}, {id: 2, author: ['b', 'c']}, {id: 3, author: ['c', 'a']}],
  },
  queries: {
    getEventByAuthors (context, authors) {
      return context.state.events.filter(e => authors.every(author => e.author.includes(author)))
    }
  }
}

Query functions receive a context object which contains store's state and getters. You can access them by context.state or context.getters, or using Object Destructuring feature in ES2015:

const options = {
  state: {
    events: [{id: 1, author: ['a', 'b']}, {id: 2, author: ['b', 'c']}, {id: 3, author: ['c', 'a']}],
  },
  queries: {
    getEventByAuthors ({state, getters}, authors) {
      return state.events.filter(e => authors.every(author => e.author.includes(author)))
    }
  }
}

Inside module queries, context will also contain rootState and rootGetters.

const options = {
  state: {
    events: [{id: 1, author: ['a', 'b']}, {id: 2, author: ['b', 'c']}, {id: 3, author: ['c', 'a']}],
  },
  computed: {
    currentAuthor (state) {
      return state.author[0]
    }
  },
  modules: {
    foo: {
      namespaced: true,
      queries: {
        getEvents ({rootState, rootGetters}, authors) {
          return rootState.events.filter(e => authors.concat(rootGetters.currentAuthor).every(author => e.author.includes(author)))
        }
      }
    }
  }
}

Before creating Vuex store, transform the options with supportQuery(options) method:

import Vuex from 'vuex'
import { supportQuery } from 'vuex-queries'
const store = new Vuex.Store(supportQuery(options))

Use mapQueries(namespace, map) method (which has the same parameters as other component binding helpers) to map component methods to query functions:

import { mapQueries } from 'vuex-queries'

export default {
  methods: {
    ...mapQueries(['getEventByAuthors'])
  },
  render () {
    return (
      <div>
        {this.getEventByAuthors(['a', 'c']).map(e => (
          <p>Event: {e.id}</p>
        ))}
      </div>
    )
  }
}

Changelog

v1.1.1

  • update peerDependencies to allow work with Vuex 3.x

v1.1.0

  • Add support for rootState & rootGetters

License

FOSSA Status

About

Vuex-Queries helps you write query functions in Vuex

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •