I have lodash imported globally with:
window._ = require('lodash'); // app.js
and it works fine when I use it on the code like in methods. But when I try to use it inside templates like:
{{_.get(user, 'address.name')}}
shows undefined error:
Property or method "_" is not defined on the instance but referenced during render
Why happen this? I could refactor creating a new variable and assign the value in code and it will work, but I want to use it directly on template too.
Extending on my comment: I usually discourage using third party util/helper methods inside VueJS template. This is, of course, a personal choice, but it is way simpler to let VueJS handle the rendering directly (and also guards against possible reactivity issues down the road). Therefore, you can simply use a computed property (or a method, if you need to pass arguments) to generate the string, which is inserted into the template.
Example:
computed: {
addressName() {
return _.get(this.user, 'address.name');
}
}
Then, in your template, you can simply use {{ addressName }}
to render the string. Should you require more dynamic use with more flexibility and abstraction, you can use methods instead. For example, if your path is going to be dynamic, you can then create a method that retrieves data from this.user
with a provided path
argument:
methods: {
userData(path) {
return _.get(this.user, path);
}
}
In your template you can simply use {{ userData('address.name') }}
.