diff --git a/.eslintignore b/.eslintignore
index cb88c73..fe762a0 100644
--- a/.eslintignore
+++ b/.eslintignore
@@ -1,3 +1,6 @@
dist
archive
-test
\ No newline at end of file
+test
+index.js
+vue-deepset.js
+vue-deepset.min.js
\ No newline at end of file
diff --git a/README.md b/README.md
index 0f85b91..91a02e8 100644
--- a/README.md
+++ b/README.md
@@ -1,13 +1,13 @@
# vue-deepset
-Deep set Vue.js objects
+Deep set Vue.js objects using dynamic paths
---
Binding deeply nested data properties and vuex data to a form or component can be tricky. The following set of tools aims to simplify data bindings. Compatible with `Vue 1.x`, `Vue 2.x`, `Vuex 1.x`, and `Vuex 2.x`
-**Note** `vueModel` and `vuexModel` use [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) objects if supported by the browser and fallback to an object with generated fields based on the target object. Because of this, it is always best to pre-define the properties of an object.
+**Note** `vueModel` and `vuexModel` use [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) objects if supported by the browser and fallback to an object with generated fields based on the target object. Because of this, it is always best to pre-define the properties of an object when using older browsers.
-Also note that models are flat and once built can set vue/vuex directly using `model[path] = value`
+Also note that models are flat and once built can set vue/vuex directly using `model[path] = value` where path is a lodash formatted path string or path array.
### Examples
@@ -18,9 +18,41 @@ Full examples can be found in the [tests](/~https://github.com/bhoriuchi/vue-deeps
* `vue@>=1.0.0`
* `vuex@>=1.0.0` (optional)
+### Dynamic paths
+
+If you knew what every path you needed ahead of time you could (while tedious) create custom computed properties with getter and setter methods for each of those properties. But what if you have a dynamic and deeply nested property? This problem was actually what inspired the creation of this library. Using a Proxy, `vue-deepset` is able to dynamically create new, deep, reactive properties as well as return `undefined` for values that are not yet set.
+
### Path Strings
-The modeling methods use `lodash.toPath` format for path strings. Please ensure references use this format
+The modeling methods use `lodash.toPath` format for path strings. Please ensure references use this format. You may also use `path Arrays` which can be easier to construct when using keys that include dots.
+
+The following 2 path values are the same
+```js
+const stringPath = 'a.b["c.d"].e[0]'
+const arrayPath = [ 'a', 'b', 'c.d', 'e', 0 ]
+```
+
+#### Keys with dots
+
+Since dots prefix a nested path and are also valid characters for a key data that looks like the following can be tricky
+
+```js
+const data = {
+ 'foo.bar': 'baz',
+ foo: {
+ bar: 'qux'
+ }
+}
+```
+
+So care should be taken when building the path string (or just use an array path) as the following will be true
+
+```js
+'foo.bar' // qux
+'["foo.bar"]' // baz
+'foo["bar"]' // qux
+'["foo"].bar' // qux
+```
### Binding `v-model` to deeply nested objects
@@ -35,7 +67,7 @@ Model objects returned by `$deepModel`, `vueModel`, and `vuexModel` are flat and
## Usage
* Webpack `import * as VueDeepSet from 'vue-deepset'`
-* Browser ``
+* Browser ``
### As a Plugin
@@ -212,9 +244,8 @@ import { vueSet } from 'vue-deepset'
export default {
methods: {
- vueSet: vueSet,
clearForm () {
- this.vueSet(this.localForm, 'message', '')
+ vueSet(this.localForm, 'message', '')
}
},
data: {
diff --git a/index.js b/index.js
index df619c7..55fa3aa 100644
--- a/index.js
+++ b/index.js
@@ -37,8 +37,11 @@ var rePropName = RegExp(
// Or match "" as the space between consecutive dots or empty brackets.
'(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))', 'g');
-// modified from lodash
+// modified from lodash - /~https://github.com/lodash/lodash
function toPath(string) {
+ if (Array.isArray(string)) {
+ return string;
+ }
var result = [];
if (string.charCodeAt(0) === charCodeOfDot) {
result.push('');
@@ -57,6 +60,14 @@ function toPath(string) {
function noop() {}
+function hasOwnProperty(object, property) {
+ return Object.prototype.hasOwnProperty.call(object, property);
+}
+
+function deepsetError(message) {
+ return new Error('[vue-deepset]: ' + message);
+}
+
function isObjectLike(object) {
return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && object !== null;
}
@@ -117,12 +128,11 @@ function getPaths(object) {
pushPaths(val, (current + '.' + key).replace(/^\./, ''), paths);
pushPaths(val, (current + '[' + key + ']').replace(/^\./, ''), paths);
pushPaths(val, (current + '["' + key + '"]').replace(/^\./, ''), paths);
- } else if (key.match(invalidKey) !== null) {
- // must quote
- pushPaths(val, (current + '["' + key + '"]').replace(/^\./, ''), paths);
- } else {
+ } else if (!key.match(invalidKey)) {
pushPaths(val, (current + '.' + key).replace(/^\./, ''), paths);
}
+ // always add the absolute array notation path
+ pushPaths(val, (current + '["' + key + '"]').replace(/^\./, ''), paths);
});
}
return [].concat(new Set(paths));
@@ -145,14 +155,6 @@ function _get(obj, path, defaultValue) {
return defaultValue;
}
-function hasOwnProperty(object, property) {
- return Object.prototype.hasOwnProperty.call(object, property);
-}
-
-function getProp(object, property) {
- return Object.keys(object).indexOf(property) === -1 ? _get(object, property) : object[property];
-}
-
function getProxy(vm, base, options) {
noop(options); // for future potential options
var isVuex = typeof base === 'string';
@@ -160,7 +162,7 @@ function getProxy(vm, base, options) {
return new Proxy(object, {
get: function get(target, property) {
- return getProp(target, property);
+ return _get(target, property);
},
set: function set(target, property, value) {
isVuex ? vuexSet.call(vm, pathJoin(base, property), value) : vueSet(target, property, value);
@@ -183,7 +185,7 @@ function getProxy(vm, base, options) {
},
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, property) {
return {
- value: getProp(target, property),
+ value: _get(target, property),
writable: false,
enumerable: true,
configurable: true
@@ -230,22 +232,30 @@ function buildVuexModel(vm, vuexPath, options) {
}
function vueSet(object, path, value) {
- var parts = toPath(path);
- var obj = object;
- while (parts.length) {
- var key = parts.shift();
- if (!parts.length) {
- _vue2.default.set(obj, key, value);
- } else if (!hasOwnProperty(obj, key) || obj[key] === null) {
- _vue2.default.set(obj, key, typeof key === 'number' ? [] : {});
+ try {
+ var parts = toPath(path);
+ var obj = object;
+ while (parts.length) {
+ var key = parts.shift();
+ if (!parts.length) {
+ _vue2.default.set(obj, key, value);
+ } else if (!hasOwnProperty(obj, key) || obj[key] === null) {
+ _vue2.default.set(obj, key, typeof key === 'number' ? [] : {});
+ }
+ obj = obj[key];
}
- obj = obj[key];
+ return object;
+ } catch (err) {
+ throw deepsetError('vueSet unable to set object (' + err.message + ')');
}
}
function vuexSet(path, value) {
- if (!this.$store) throw new Error('[vue-deepset]: could not find vuex store object on instance');
- this.$store[this.$store.commit ? 'commit' : 'dispatch']('VUEX_DEEP_SET', { path: path, value: value });
+ if (!isObjectLike(this.$store)) {
+ throw deepsetError('could not find vuex store object on instance');
+ }
+ var method = this.$store.commit ? 'commit' : 'dispatch';
+ this.$store[method]('VUEX_DEEP_SET', { path: path, value: value });
}
function VUEX_DEEP_SET(state, _ref) {
@@ -264,7 +274,7 @@ function extendMutation() {
function vueModel(object, options) {
var opts = Object.assign({}, options);
if (!isObjectLike(object)) {
- throw new Error('[vue-deepset]: invalid object specified for vue model');
+ throw deepsetError('invalid object specified for vue model');
} else if (opts.useProxy === false || typeof Proxy === 'undefined') {
return buildVueModel(this, object, opts);
}
@@ -274,9 +284,11 @@ function vueModel(object, options) {
function vuexModel(vuexPath, options) {
var opts = Object.assign({}, options);
if (typeof vuexPath !== 'string' || vuexPath === '') {
- throw new Error('[vue-deepset]: invalid vuex path string');
+ throw deepsetError('invalid vuex path string');
+ } else if (!isObjectLike(this.$store) || !isObjectLike(this.$store.state)) {
+ throw deepsetError('no vuex state found');
} else if (!has(this.$store.state, vuexPath)) {
- throw new Error('[vue-deepset]: Cannot find path "' + vuexPath + '" in Vuex store');
+ throw deepsetError('cannot find path "' + vuexPath + '" in Vuex store');
} else if (opts.useProxy === false || typeof Proxy === 'undefined') {
return buildVuexModel(this, vuexPath, opts);
}
@@ -288,8 +300,7 @@ function deepModel(base, options) {
}
function install(VueInstance) {
- VueInstance.prototype.$vueModel = vueModel;
- VueInstance.prototype.$vuexModel = vuexModel;
VueInstance.prototype.$deepModel = deepModel;
VueInstance.prototype.$vueSet = vueSet;
+ VueInstance.prototype.$vuexSet = vuexSet;
}
diff --git a/package.json b/package.json
index 07d78d8..f433b3e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "vue-deepset",
- "version": "0.6.0",
+ "version": "0.6.1",
"description": "Deep set Vue.js objects",
"main": "index.js",
"scripts": {
diff --git a/src/index.js b/src/index.js
index c26792f..5a4b68c 100644
--- a/src/index.js
+++ b/src/index.js
@@ -18,8 +18,11 @@ const rePropName = RegExp(
'(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))'
, 'g')
-// modified from lodash
+// modified from lodash - /~https://github.com/lodash/lodash
function toPath (string) {
+ if (Array.isArray(string)) {
+ return string
+ }
const result = []
if (string.charCodeAt(0) === charCodeOfDot) {
result.push('')
@@ -38,13 +41,21 @@ function toPath (string) {
function noop () {}
+function hasOwnProperty (object, property) {
+ return Object.prototype.hasOwnProperty.call(object, property)
+}
+
+function deepsetError (message) {
+ return new Error(`[vue-deepset]: ${message}`);
+}
+
function isObjectLike (object) {
return typeof object === 'object' && object !== null
}
function pathJoin (base, path) {
try {
- let connector = path.match(/^\[/) ? '' : '.'
+ const connector = path.match(/^\[/) ? '' : '.'
return `${base || ''}${base ? connector : ''}${path}`
} catch (error) {
return ''
@@ -96,11 +107,11 @@ function getPaths (object, current = '', paths = []) {
pushPaths(val, `${current}.${key}`.replace(/^\./, ''), paths)
pushPaths(val, `${current}[${key}]`.replace(/^\./, ''), paths)
pushPaths(val, `${current}["${key}"]`.replace(/^\./, ''), paths)
- } else if (key.match(invalidKey) !== null) { // must quote
- pushPaths(val, `${current}["${key}"]`.replace(/^\./, ''), paths)
- } else {
+ } else if (!key.match(invalidKey)) {
pushPaths(val, `${current}.${key}`.replace(/^\./, ''), paths)
}
+ // always add the absolute array notation path
+ pushPaths(val, `${current}["${key}"]`.replace(/^\./, ''), paths)
})
}
return [ ...new Set(paths) ]
@@ -109,9 +120,7 @@ function getPaths (object, current = '', paths = []) {
function get (obj, path, defaultValue) {
try {
let o = obj
- const fields = Array.isArray(path)
- ? path
- : toPath(path)
+ const fields = Array.isArray(path) ? path : toPath(path)
while (fields.length) {
const prop = fields.shift()
o = o[prop]
@@ -125,16 +134,6 @@ function get (obj, path, defaultValue) {
return defaultValue
}
-function hasOwnProperty (object, property) {
- return Object.prototype.hasOwnProperty.call(object, property)
-}
-
-function getProp (object, property) {
- return Object.keys(object).indexOf(property) === -1
- ? get(object, property)
- : object[property]
-}
-
function getProxy (vm, base, options) {
noop(options) // for future potential options
const isVuex = typeof base === 'string'
@@ -142,7 +141,7 @@ function getProxy (vm, base, options) {
return new Proxy(object, {
get: (target, property) => {
- return getProp(target, property)
+ return get(target, property)
},
set: (target, property, value) => {
isVuex
@@ -167,7 +166,7 @@ function getProxy (vm, base, options) {
},
getOwnPropertyDescriptor: (target, property) => {
return {
- value: getProp(target, property),
+ value: get(target, property),
writable: false,
enumerable: true,
configurable: true
@@ -206,22 +205,30 @@ function buildVuexModel (vm, vuexPath, options) {
}
export function vueSet (object, path, value) {
- const parts = toPath(path)
- let obj = object
- while (parts.length) {
- const key = parts.shift()
- if (!parts.length) {
- Vue.set(obj, key, value)
- } else if (!hasOwnProperty(obj, key) || obj[key] === null) {
- Vue.set(obj, key, typeof key === 'number' ? [] : {})
+ try {
+ const parts = toPath(path)
+ let obj = object
+ while (parts.length) {
+ const key = parts.shift()
+ if (!parts.length) {
+ Vue.set(obj, key, value)
+ } else if (!hasOwnProperty(obj, key) || obj[key] === null) {
+ Vue.set(obj, key, typeof key === 'number' ? [] : {})
+ }
+ obj = obj[key]
}
- obj = obj[key]
+ return object
+ } catch (err) {
+ throw deepsetError(`vueSet unable to set object (${err.message})`)
}
}
export function vuexSet (path, value) {
- if (!this.$store) throw new Error('[vue-deepset]: could not find vuex store object on instance')
- this.$store[this.$store.commit ? 'commit' : 'dispatch']('VUEX_DEEP_SET', { path, value })
+ if (!isObjectLike(this.$store)) {
+ throw deepsetError('could not find vuex store object on instance')
+ }
+ const method = this.$store.commit ? 'commit' : 'dispatch'
+ this.$store[method]('VUEX_DEEP_SET', { path, value })
}
export function VUEX_DEEP_SET (state, { path, value }) {
@@ -235,7 +242,7 @@ export function extendMutation (mutations = {}) {
export function vueModel (object, options) {
const opts = Object.assign({}, options)
if (!isObjectLike(object)) {
- throw new Error('[vue-deepset]: invalid object specified for vue model')
+ throw deepsetError('invalid object specified for vue model')
} else if (opts.useProxy === false || typeof Proxy === 'undefined') {
return buildVueModel(this, object, opts)
}
@@ -245,9 +252,11 @@ export function vueModel (object, options) {
export function vuexModel (vuexPath, options) {
const opts = Object.assign({}, options)
if (typeof vuexPath !== 'string' || vuexPath === '') {
- throw new Error('[vue-deepset]: invalid vuex path string')
+ throw deepsetError('invalid vuex path string')
+ } else if (!isObjectLike(this.$store) || !isObjectLike(this.$store.state)) {
+ throw deepsetError('no vuex state found')
} else if (!has(this.$store.state, vuexPath)) {
- throw new Error(`[vue-deepset]: Cannot find path "${vuexPath}" in Vuex store`)
+ throw deepsetError(`cannot find path "${vuexPath}" in Vuex store`)
} else if (opts.useProxy === false || typeof Proxy === 'undefined') {
return buildVuexModel(this, vuexPath, opts)
}
@@ -261,8 +270,7 @@ export function deepModel (base, options) {
}
export function install (VueInstance) {
- VueInstance.prototype.$vueModel = vueModel
- VueInstance.prototype.$vuexModel = vuexModel
VueInstance.prototype.$deepModel = deepModel
VueInstance.prototype.$vueSet = vueSet
+ VueInstance.prototype.$vuexSet = vuexSet
}
diff --git a/test/issue9.html b/test/issue9.html
index 2de0026..4381ac1 100644
--- a/test/issue9.html
+++ b/test/issue9.html
@@ -12,6 +12,12 @@
+
+
+
+
+
+