all files / src/ install.ts

100% Statements 29/29
100% Branches 6/6
100% Functions 3/3
100% Lines 26/26
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48        17×                                    
import { VueConstructor, Option } from './interfaces'
import LSStorage from './lsstorage'
import { set, copy } from './objpath'
 
import assign from './assign'
 
export function install(Vue: VueConstructor) {
	Vue.mixin({
		created() {
			if ('storage' in this.$options) {
				const option: Option = this.$options.storage
				const { keys, merge = assign, namespace: ns } = option
 
				const ls = new LSStorage(option)
 
				let optdata = {}
				for (const k of keys) {
					copy(optdata, this, k)
				}
 
				let data = null
				if (ls.has(ns)) {
					data = merge(optdata, ls.get(ns))
					ls.set(ns, data)
				} else {
					const tmp = {}
					for (const k of keys) {
						copy(tmp, optdata, k)
					}
					data = tmp
					ls.set(ns, data)
				}
 
				for (const k of keys) {
					copy(this, data, k)
					this.$watch(k, {
						handler: value => {
							set(data, k, value)
							ls.set(ns, data)
						},
						deep: true
					})
				}
			}
		}
	})
}