Store component properties in localStorage using the @Persist()
decorator with vue class components. Properties will be stored on change and restored from localStorage when the component mounts.
import Vue from 'vue'
import Component from 'vue-class-component'
import { Persist } from 'vue-persist-decorator'
@Component
export default class App extends Vue {
@Persist()
myProperty = 'default value'
}
yarn add -D vue-persist-decorator
or
npm i vue-persist-decorator --save-dev
The @Persist
decorator can receive an options object with the following properties:
Properties can be set to expire using relative time. If the expiry date has passed when the component mounts, the value will not be restored. The relative time string is a number + ms/s/m/h/d. If no unit of time is provided the number will default to hours.
@Component
export default class App extends Vue {
@Persist({ expiry: '5m' })
myProperty = 'I will only be restored within 5 minutes of being changed.'
}
Set a custom key for the persist object in localStorage. By default the key name is componentName_propertyName
.
@Component
export default class App extends Vue {
@Persist({ key: 'custom_local_storage_key' })
myProperty = 'By default my localStorage key would be app_myProperty.'
}
Vue watcher option, defaults to true. Set this to false if you don't want changes to nested values to cause your property to be stored.
@Component
export default class App extends Vue {
@Persist({ deep: false })
myProperty = {
hello: 'Changing the value of hello directly will not cause myProperty to be stored if deep is false.',
}
}
Vue watcher option, defaults to false.