A Vue.js plugin that makes it easy to share reactive data between components.
$ npm install vue-stash
import Vue from 'vue';
import VueStash from 'vue-stash';
Vue.use(VueStash)
or
window.Vue = require('vue');
require('vue-stash');
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'
}
}
Example 1: Simplest usage
Vue.component('user-card', {
store: ['user'],
ready() {
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'
},
ready() {
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'
},
ready() {
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';
}
},
ready() {
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.
This plugin sets Vue.prototype.$store
which allows any component to access the store via vm.$store
.
Vue.component('user-card', {
ready() {
console.log(this.$store.user.name); // 'cody';
this.$store.user.name = 'john doe';
console.log(this.$store.user.name); // 'john doe';
}
});
If you'd like to demo vue-stash
try vue-mix