Easily share reactive data between your Vue components.

Overview

vue-stash

A Vue.js plugin that makes it easy to share reactive data between components.

This plugin is best suited for the rapid development of prototypes. This plugin is not intended to be used for complex applications. For complex applications I would recommend the official VueJS state management plugin, Vuex

Installation

1.) Install package via NPM
$ npm install vue-stash
2.) Install plugin within project.
import Vue from 'vue';
import VueStash from 'vue-stash';

Vue.use(VueStash)

or

window.Vue = require('vue');
require('vue-stash');

Usage

1.) Initialize your store object.

Your store object is nothing more than a simple Javascript object set within your root vue model's $data option; Think of it as your "shared data option". Make sure you pre-initialize any properties that you want to be reactive, just like always.

new Vue({
    el: '#app',
    data: {
        store: {
            user: {
                name: 'cody'
            }
        }
    }
})

Alternatively, you can import your store from another file.

import store from './store';

new Vue({
    el: '#app',
    data: { store }
})

store.js

export default {
    user: {
        name: 'cody'
    }
}
2.) Add a "store" option to any child components that need to access data from the store.

Example 1: Simplest usage

Vue.component('user-card', {
    store: ['user'],
    // Use `ready` for Vue 1.x
    mounted() {
        console.log(this.user.name); // 'cody'
        this.user.name = 'john doe';
        console.log(this.user.name); // 'john doe'
    }
});

Example 2: Object store

Vue.component('user-card', {
    store: {
        user: 'user'
    },
    // Use `ready` for Vue 1.x
    mounted() {
        console.log(this.user.name); // 'cody'
        this.user.name = 'john doe';
        console.log(this.user.name); // 'john doe'
    }
});

Example 3: Access nested store property

Vue.component('user-card', {
    store: {
        name: 'user.name'
    },
    // Use `ready` for Vue 1.x
    mounted() {
        console.log(this.name); // 'cody'
        this.name = 'john doe';
        console.log(this.name); // 'john doe'
    }
});

Example 4: Dynamic store access

Vue.component('user-card', {
    store: {
        name() {
            return 'user.name';
        }
    },
    // Use `ready` for Vue 1.x
    mounted() {
        console.log(this.name); // 'cody'
        this.name = 'john doe';
        console.log(this.name); // 'john doe'
    }
});

Note: The end result of examples 1-4 are equivalent.

3.) Access the store directly.

This plugin sets Vue.prototype.$store which allows any component to access the store via vm.$store.

Vue.component('user-card', {
    // Use `ready` for Vue 1.x
    mounted() {
        console.log(this.$store.user.name); // 'cody';
        this.$store.user.name = 'john doe';
        console.log(this.$store.user.name); // 'john doe';
    }
});

Demo

If you'd like to demo vue-stash try vue-mix

License

MIT

Comments
  • Reactivity with Arrays

    Reactivity with Arrays

    Hello,

    Thanks for the plugin, it's exactly what I was looking for 👍

    Is there any way the plugin could extend arrays in the store with $set like Vue does? Right now I'm having to use splice to keep the store reactive for arrays.

    enhancement 
    opened by matt-allan 8
  • Call an api from store

    Call an api from store

    Hi,

    is it possible to make an api call from store? I would like to call an endpoint when the store is created.

    My store.js

    export default { user: { name: null } }

    opened by ServerJunge 6
  • How to use with nested properties of store

    How to use with nested properties of store

    In your example the store object doesn't have any nested properties. If the store has nested properties like:

    store:{   
    
         user:{  
               name:'',  
               address:{  
                    block:'',
                    street:'',
                    city:''
               },
               role:'',
               department:{
                     name:'',
                     division:{
                           name:'',
                           subDivision:{
                                name:'',
                                projects:[{team:'', leader:'', 'type:''}]
                           }
                      }
               }
       }  
    }
    

    Then how do you write the get and set function of the Store Accessor?

    enhancement 
    opened by neeravp 6
  • Child component not getting updated

    Child component not getting updated

    So I have a parent component

    {
    data() { return {store: { userId: null }} }
    }
    

    and I have a child component

    {
    store:['userId'], data { return { id: function(){ return this.$store.userId }}}, watch { id: function(){ console.log(this.id) } }
    }
    

    But

    watch does not fire

    I need to keep a piece of data for parent-child not globally. Do I still need to have a store.js?

    opened by karneaud 4
  • Promises for remote API

    Promises for remote API

    Hi there,

    great library you are maintaining for us. I appreciate how simple it is. With all this simplicity do you think some promise handling would fit in?

    Imagine I have 2 components: Root, Child.

    In Root.vue, I fetch item and assign it to the store upon app init:

    store: {
      item: 'path.to.item' 
    }
    
    mounted() {
        itemService
           .get(itemId)
           .then(item => {
                this.item = item
           })
    }
    

    In Child.vue, I want to use item but it hasn't been fetched yet.

    store: {
      item: 'path.to.item' 
    }
    
    mounted() {
        const itemKey = this.item.key // this.item is undefined
    }
    

    Is there some strategy how to handle it without modifying vue-stash? Or does need some promise support to handle this case?

    opened by zatziky 3
  • Understanding

    Understanding

    Hi,

    I installed vue stash via npm and followed the instruction. I have two components. In the first component I call axios to update the username and set the username in the store. In my second component I have a navbar with username. Shouldn't they username be updated?

    Thanks for you great work so far 👍

    opened by Wipsly 3
  • Reset store to intial state

    Reset store to intial state

    How would you go about resetting the store to the initial state (intial state declared in separate files and imported)... without manually resetting all the properties of the state?

    opened by mkelley82 3
  • componet not picking up store

    componet not picking up store

    I have a store within my main vue instance which is working fine and has data. I am trying to access that data within a component...

    mounted() {
       this.list = this.$store.list;
       console.log('jobs' + this.$store.list);
    },
    

    But list is not populated, although I can see within vue dev tools that the list within the store on the root is populated.

    Am I missing something?

    opened by jigsawsoul 3
  • TypeScript support

    TypeScript support

    Is there any way to use this plugin in TypeScript class component ?

    import Vue from 'vue'
    import Component from 'vue-class-component'
    
    @Component({
      name: 'MyComponent'
    })
    export default class MyComponent extends Vue {
      message = 'Hello from MyComponent'
    }
    

    Any idea ? thanks

    opened by ozeebee 3
  • Computed store properties?

    Computed store properties?

    Hi,

    is it possible to use computed properties with vue-stash?

    like

    store: {
      val1: true
      $computed: {
         derived: function() { return this.$store.val1 ? 'yes' : 'no' }
      }
    }
    
    opened by psi-4ward 3
  • Is vue-stash still maintained?

    Is vue-stash still maintained?

    Hi @cklmercer

    I like the idea of a very simple way to "inject" parts of the global store into a component, such as is done in vue-stash. However, before I actually start using vue-stash I wanted to know if you were planning on maintaining it further. Especially since I see that there has been no activity in this repo since September 2016 and there are a couple of issues open, one with a promise to look into it asap.

    Thanks Paul

    opened by pbastowski 3
  • Hoist to global scope and rename store?

    Hoist to global scope and rename store?

    Hi,

    I'd like to be able to use vue-stash in a way that I can simply type $db to access my data instead of this.$store.

    For example, if this.$store.test were to have a value of 'testing' then I could simply write console.log($db.test) and get the word 'testing' output into my console.

    Is this possible while retaining reactivity of the data?

    opened by AJB99 0
  • some way to add keys to store

    some way to add keys to store

    Hi! Very nice library and I am using it for a long time. Thank you! One question: is there any way to add new key or sub key to store? Maybe something like store.$set('key.subkey', value)?

    opened by fend25 1
  • Install from cdn

    Install from cdn

    Hello! I don't always use webpack in projects, I would like to see the way how to connect vue-stash via cdn without Vue.use. (Vue-router and vuex has this capability)

    I tried include from https://www.jsdelivr.com/package/npm/vue-stash But console says "ReferenceError: exports is not defined"

    opened by webkitten 2
Releases(v2.0.0-beta)
Owner
Cody Mercer
Cody Mercer
💾🔗🖥️ Share, synchronize and persist state between multiple tabs with this plugin for Vuex. TypeScript types included.

vuex-multi-tab-state This Vuex plugin allows you to sync and share the status of your Vue application across multiple tabs or windows using the local

Gabriel Martín Blázquez 155 Nov 19, 2022
💾 Persist and rehydrate your Vuex state between page reloads.

vuex-persistedstate Persist and rehydrate your Vuex state between page reloads. Install npm install --save vuex-persistedstate The UMD build is also a

Robin van der Vleuten 5.8k Jan 5, 2023
Keep your vuex state between page reloads.

vuex-persisted-states Keep your vuex states between page reloads. 在页面重新加载之间保持您的 vuex 状态 原理: 借助缓存机制来存储 vuex 状态 安装(Install) npm install vuex-persisted-s

Chengbotao 2 Mar 7, 2022
Flexible binding between Vue and Redux

vuejs-redux Description Flexible binding between Vue and Redux, allowing use of multiple stores. It works, in the same way, like render props does in

Titouan CREACH 58 Nov 24, 2022
Vuex state synchronization between iframe/window

vuex-iframe-sync English | 中文 Vuex state synchronization between iframe/window Your star is the greatest encouragement to me. ✨ Features: support ifra

Jiahui.Liang 101 Dec 17, 2022
Vuex state persistance and synchronization between tabs/windows.

vuex-basement Vuex state persistance and synchronization between tabs/windows. Tested to work with Vue2. One Shortcomming (please read before use). Th

Rashad Saleh 65 Jun 29, 2022
DruxtJS; A bridge between frameworks.

DruxtJS; A bridge between frameworks. Druxt = DRUpal + nUXT = Fully Decoupled Drupal. Links Documentation: https://druxtjs.org Community Discord serve

DruxtJS 93 Dec 14, 2022
Type-safe reactive state management

rxsv Framework agnostic minimal state management library based on RxJS, heavily inspired by Redux and Redux-Observable with limited boilerplate and Ty

Grzegorz Bielski 22 Jun 28, 2022
A state management library for React combined immutable, mutable and reactive mode

Welcome to bistate ?? Create the next immutable state tree by simply modifying the current tree bistate is a tiny package that allows you to work with

工业聚 119 Jan 8, 2023
vuex-module-generator - It allows you to create a vuex module easily.

Vuex Module Generator (VMG) VMG allows you to create a vuex module easily. See All implementations. See Customer Example. Supported module types Clone

Abdullah 91 Dec 28, 2022
A util package to use Vuex with Composition API easily.

vuex-composition-helpers A util package to use Vuex with Composition API easily. Installation $ npm install vuex-composition-helpers This library is n

Greenpress 276 Dec 30, 2022
:hammer: Utilities for vuex to easily create and manage actions.

vuex-action Utilities for vuex to easily create and manage actions. Allow you to create untyped action Support for Promise Work with [email protected] and [email protected] I

varHarrie 27 Mar 26, 2021
☘️ A package that dynamically registers your components and vuex modules

Vue Registrar A dynamic component registrar and Vuex module assembler A Vue.js package that makes your code a lot cleaner and much more understandable

Evryn.dev 17 Mar 3, 2022
Vue and Vuex plugin to persistence data with localStorage/sessionStorage

vuejs-storage Vue.js and Vuex plugin to persistence data with localStorage/sessionStorage Purpose This plugin provide a simple binding with localStora

maple 119 Dec 15, 2022
Enable two-way data binding for form fields saved in a Vuex store

vuex-map-fields Enable two-way data binding for form fields saved in a Vuex store. Install npm install --save vuex-map-fields Basic example The follow

Markus Oberlehner 1.4k Dec 2, 2022
Use a JSONAPI api with a Vuex store, with data restructuring/normalization.

jsonapi-vuex A module to access JSONAPI data from an API, using a Vuex store, restructured to make life easier. Vue 3 - v5 and later supports only Vue

Matthew Richardson 145 Dec 22, 2022
A plugin for syncing Vuex store with js-data

vuex-jsdata-plugin A simple attempt to help using jsdata alongside Vue.js: This plugin syncing Vuex store with js-data After each injection made by js

Alexandre Bonaventure Geissmann 20 Jul 30, 2020
A tiny Vue plugin that connects components with Redux

redux-connect-vue **Note: redux-connect-vue v3 is compatible with Vue 3.x. If you are looking for a Vue 2.x compatible version, check out v2 A tiny Vu

Kai Johnson 3 May 23, 2022
Library for connecting MobX to native Web Components with a Vue-like template binding syntax

ElemX.js ElemX is a proof-of-concept front-end javascript library for connecting MobX to native Web Components with a Vue-like template binding syntax

Alan Graham 15 Nov 28, 2022