Created
October 25, 2016 08:27
-
-
Save sebastiandedeyne/58d2a9f44de6dffa80df301c3e83cb84 to your computer and use it in GitHub Desktop.
Helper to inject ancestor options in a Vue component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inject from './inject'; | |
import Vue from 'vue'; | |
const Level3 = { | |
template: '<div>{{ greeting }}</div>', | |
mixins: [ | |
inject('translations', 'user') | |
], | |
computed: { | |
greeting() { | |
return this.$translations.greeting(this.$user.name); | |
}, | |
}, | |
}; | |
const Level2 = { | |
template: '<div><level-3></level-3></div>', | |
components: { | |
Level3, | |
}, | |
user: { | |
name: 'Sebastian', | |
}, | |
}; | |
const Level1 = { | |
template: '<div><level-2></level-2></div>', | |
components: { | |
Level2, | |
}, | |
}; | |
new Vue({ | |
el: '#app', | |
template: '<div><level-1></level-1></div>', | |
components: { Level1 }, | |
translations: { | |
greeting: name => `Hello ${name}!`, | |
}, | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function resolveDependency(key, vm) { | |
if (key in vm.$options) { | |
return vm.$options[key]; | |
} | |
if (vm.$options.parent) { | |
return resolveDependency(key, vm.$options.parent); | |
} | |
throw new Error(`Dependency \`${key}\` couldn't be resolved`); | |
} | |
const inject = (...keys) => ({ | |
beforeCreate() { | |
keys.forEach(key => this[`$${key}`] = resolveDependency(key, this), this); | |
}, | |
}); | |
export default inject; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment