项目作者: arve0

项目描述 :
Persist state to localstorage
高级语言: JavaScript
项目地址: git://github.com/arve0/vue-persistent-state.git
创建时间: 2017-10-06T17:20:47Z
项目社区:https://github.com/arve0/vue-persistent-state

开源协议:

下载


Vue persistent state

This plugin lets you persist state in Vue through localStorage. Nice for prototyping and small projects, when vuex is too much.

Install

  1. npm install vue-persistent-state

Usage

  1. import Vue from 'vue'
  2. import persistentState from 'vue-persistent-state'
  3. let initialState = {
  4. str: 'persist me',
  5. obj: {
  6. a: 'nested object'
  7. },
  8. number: 42,
  9. arr: ['item 0']
  10. }
  11. Vue.use(persistentState, initialState)
  12. // initialState is injected as data in all vue instances
  13. // any changes to state will be stored in localStorage

This gives you a global mutable state, available in all Vue instances. Any changes to state will be stored in localStorage. If the page is refreshed, initialState is merged with state from localStorage.

You can mix this with local state in components, data will be merged and local state takes preference if there are any name crashes. To avoid name crashes you might want to use a namespace:

  1. let initialState = {
  2. persisted: {
  3. str: 'persisted state under namespace `persisted`'
  4. }
  5. }
  6. Vue.use(persistentState, initialState)

If you need access to localStorage, $store is available. Example:

  1. new Vue({
  2. methods: {
  3. reset: function () {
  4. // remove all state from localStorage
  5. // NOTE: does not alter state
  6. this.$store.clearAll()
  7. // if you need to alter state too, this might be better:
  8. this.persistedProperty = []
  9. }
  10. }
  11. })

store has the methods set, get, remove, clearAll and each. For more, see store API.

Full example and demo

Demo

  1. import Vue from 'vue/dist/vue.esm.js'
  2. import persistentState from 'vue-persistent-state'
  3. let initialState = {
  4. str: 'persist me',
  5. obj: {
  6. a: 'nested object'
  7. },
  8. number: 42,
  9. arr: ['item 0']
  10. }
  11. // inject initialState as data
  12. Vue.use(persistentState, initialState)
  13. // works with components too
  14. Vue.component('a-component', {
  15. template: `<span>Array contents: {{arr.join(', ')}}</span>`
  16. })
  17. new Vue({
  18. el: '#app',
  19. template: `
  20. <div>
  21. <input v-model="str">
  22. <button @click="arr.push(str)">Add to array</button><br>
  23. <input v-model="obj.a"><br>
  24. {{ number }} <button @click="number++">Inc</button><br>
  25. <a-component></a-component><br>
  26. <button @click="reload">Reset</button><br><br>
  27. State is persisted, try refreshing the page!<br>
  28. </div>`,
  29. methods: {
  30. reload: function () {
  31. // remove all persisted state
  32. this.$store.clearAll()
  33. // reload page
  34. window.location.reload()
  35. }
  36. }
  37. })

License

ISC