Skip to content

Instantly share code, notes, and snippets.

@zmmbreeze
Created April 12, 2017 11:39
Show Gist options
  • Save zmmbreeze/c3547684942e0ad57ca9a605de7a44c5 to your computer and use it in GitHub Desktop.
Save zmmbreeze/c3547684942e0ad57ca9a605de7a44c5 to your computer and use it in GitHub Desktop.
export default {
methods: {
/**
* find all sub components
* @param {string|function} name component name or validate function.
* @return {Array.<Vue>} result.
*/
findComponents(name) {
const find = (result, child) => {
const isFound = typeof name === 'string'
? child.$options.name === name
: name(child);
if (isFound) {
result.push(child);
return result;
}
return child.$children
? child.$children.reduce(find, result)
: result;
};
return this.$children.reduce(find, []);
},
/**
* find one sub component
* @param {string|function} name component name or validate function.
* @return {Vue} result.
*/
findComponent(name) {
let found;
const find = (child) => {
const isFound = typeof name === 'string'
? child.$options.name === name
: name(child);
if (isFound) {
found = child;
return true;
}
return child.$children
? child.$children.some(find)
: false;
};
this.$children.some(find);
return found;
},
/**
* find ancestor with specified component name.
* @param {string} name component name.
* @return {Vue} ancestor
*/
findAncestor(name) {
var parent = this.$parent;
if (!parent) {
return;
}
var parentName = parent.$options.name;
while (parent && (!parentName || parentName !== name)) {
parent = parent.$parent;
if (parent) {
parentName = parent.$options.name;
}
}
return parent;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment