|
| 1 | +'use strict' |
| 2 | + |
| 3 | +export default (options) => { |
| 4 | + function get (name, cookie) { |
| 5 | + const resource = cookie ?? document.cookie |
| 6 | + |
| 7 | + let string = resource.match(`(?:(?:^|.*; *)${name} *= *([^;]*).*$)|^.*$`)[1] |
| 8 | + if (string) { |
| 9 | + string = decodeURIComponent(string) |
| 10 | + } |
| 11 | + if (string === 'undefined' |
| 12 | + || string === undefined |
| 13 | + || string === '' |
| 14 | + ) { |
| 15 | + string = null |
| 16 | + } |
| 17 | + |
| 18 | + return JSON.parse(string) |
| 19 | + } |
| 20 | + |
| 21 | + function set (name, value) { |
| 22 | + let maxAge = 0 |
| 23 | + |
| 24 | + // If options contains maxAge then we're configuring max-age. |
| 25 | + if (options.maxAge) { |
| 26 | + maxAge = options.maxAge |
| 27 | + } |
| 28 | + |
| 29 | + // If options contains days then we're configuring max-age. |
| 30 | + if (options.days) { |
| 31 | + maxAge = options.days * 60 * 60 * 24 |
| 32 | + } |
| 33 | + |
| 34 | + // Finally, creating the key. Must set `path=/` in the cookie or Firefox |
| 35 | + // won't remove the expired cookie automatically until the browser is |
| 36 | + // closed. |
| 37 | + document.cookie = `${name}=${encodeURIComponent(value)}; max-age=${maxAge}; path=/` |
| 38 | + } |
| 39 | + |
| 40 | + function drop (name) { |
| 41 | + document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/' |
| 42 | + } |
| 43 | + |
| 44 | + // observe, eye, spy, note, track, follow, guard, study, mark, monitor. |
| 45 | + function observe (ref, name) { |
| 46 | + // https://vuejs.org/api/reactivity-core.html#watch |
| 47 | + watch(ref, (newVal, prevVal) => { |
| 48 | + // Uncomment to see the result. |
| 49 | + // console.log('newVal =', newVal) |
| 50 | + // console.log('count.value =', count.value) |
| 51 | + |
| 52 | + // Stringify the reactive object before storing. |
| 53 | + set(name, JSON.stringify(ref.value)) |
| 54 | + }, { |
| 55 | + // Force deep traversal of the source if it is an object, so that the |
| 56 | + // callback fires on deep mutations. |
| 57 | + deep: true |
| 58 | + }) |
| 59 | + } |
| 60 | + |
| 61 | + return { |
| 62 | + get, |
| 63 | + set, |
| 64 | + drop, |
| 65 | + observe |
| 66 | + } |
| 67 | +} |
0 commit comments