Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I created a basic custom filter for my vue.js app which I intend to use extensively for y API variables. This is the filter in my app.js file:

filters: {
   myFilter: function(val) {
   return val.toFixed(0)
  }
},

In my index.html I simply call it like this

<p> {{ foo.bar.num | myFilter }} </p>

This returns an error. Cannot read property 'toFixed' of undefined. The problem is foo.bar.num is not defined until the API is loaded. The API has so many variables I want to use for my custom filter that it would be impractical to pre-define them all in the data option.

What would be the best approach in this case?

share|improve this question
up vote 0 down vote accepted

Give it a default value:

return typeof val == 'undefined' ? 0 : val.toFixed(0)

The warning is not from the filter but is from <p> {{ foo.bar.num }} </p>. The way to solve that would be to define:

data() {
  return {
    foo:{bar:{num:0}}}
  }
}

in your component. This can be overkill, and sometimes you don't know the structure of the object already. Anyway, the warning only shows when Vue.config.debug is true, so it should go away in production.

share|improve this answer
    
The solution nows gives me a warning, [Vue warn]: Error when evaluating expression "foo.bar.num". but at least it's not breaking the app. I'll accept your answer, and will upvote any solution that spares me of the console warning. – harrypujols Apr 28 '16 at 13:42
    
see edits for the warning – Jeff Apr 28 '16 at 15:14

Did'nt test this but did you tried one of the lifecycle hooks?

Keep

<p> {{ foo.bar.num }} </p>

And do

var Foo = new Vue({
    // el and data and stuff
    ready: function () {
       this.$options.filters.myFilter(this.foo.bar.num);
    }
});

Another approach might be the computed option: http://vuejs.org/api/#computed

share|improve this answer
    
Thanks. While this is viable, it would also be impractical to apply it to a large amount of variables. – harrypujols Apr 28 '16 at 13:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.