Filters in Vue only work with interpolation, they don’t work with v-text. Why?

Asked

Viewed 129 times

2

I know to use a filter on Vue, you can make the call as follows:

Vue.filter('hello', function (input) {
      return "hello, " + input;
})

new Vue({
  el: "#app",
  
  data: {
     name: "Wallace",
  }
  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">

    {{ name | hello }}
</div>

That is, through interpolation, it is possible to call a filter perfectly.

The problem is when I try to use the v-text. It seems that Vue behaves differently in these cases.

Vue.filter('hello', function (input) {
      return "hello, " + input;
})

new Vue({
  el: "#app",
  
  data: {
     name: "Wallace",
  }
  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">

    <span v-text="name | hello"></span>
</div>

Note that when running, an error appears:

hello is not defined

In this case, I come from Angularjs and know that it is possible to use the filters so much with ng-bind as with interpolation.

But in the case of Vue? Why doesn’t it work?

I saw no detail in the documentation regarding this.

Is there any way to circumvent this problem?

1 answer

4


In the session on documentation filters talks about it. More specifically in the part that says:

Filters are usable in two Places: mustache interpolations and v-bind Expressions.

Then the solution would be to use mustache even.

In the documentation of v-text is mentioned:

<span v-text="msg"></span>
<!-- same as -->
<span>{{msg}}</span>

Then we’d just use interpolation. Unless you have some reason to use v-text instead of interpolation.

Vue.filter('hello', function (input) {
      return "hello, " + input;
})

new Vue({
  el: "#app",
  data: {
     name: "Wallace",
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">
    <span>{{ name | hello }}</span>
</div>

  • Where is the button to react with "Sad". Sad Vue does not have it, but thanks for the information.

  • Curiosity: mustache would be the interpolation syntax? The {{ }}?

  • 1

    Yes... for some reason the gringos called the {{ }} of mustache because saporrah look like whiskers. : D

  • But man, I see no reason not to use interpolation. core from Vue do not apply filters to attr either. hahaha

  • I like to use the v-text not take the risk of the user seeing the {{ }} and also because it’s boring to be defining this in Laravel, kkkkk

  • Putz... now I get it. It makes sense. v-Cloak that helps in this.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.