Home » vue » How to use filters in VueJs to filter the input value?

How to use filters in VueJs to filter the input value?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I developed one filter to replace string, this filter works very well if I user it like :
External link{{updateTraining.externalUrl|replaceHttp}}

I would like to use it also in the input value v-model="updateTraining.externalUrl |replaceHttp " but it’s not working !

                                    <div class="col-sm-12">
                                        <div class="form-group">
                                            <label for="inputTitle">External link{{updateTraining.externalUrl|replaceHttp}}</label>
                                             <input autocomplete="nope" class="form-control" id="externalUrl"
                                                    placeholder="External link" type="text"
                                                    v-model="updateTraining.externalUrl">
                                            <small class="form-text  text-danger" v-if="errors.externalUrl"> {{errors.externalUrl[0]}} </small>
                                        </div>
                                    </div>

The error message is :

Property or method "replaceHttp" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
Answers:

You cannot use a filter like this v-model="data | filter" as v-model is a custom directive from vue.

If you want to apply a filter using v-model you need to use a computed property like so

<input v-model="filteredData" />

export default{
  data(){
       return {
              data: ''
          }
    }
},
computed: {
    filteredData: {
         get() {
            // do whatever filtering
            return this.data
         },
         set(newValue) {
           // do whatever filtering
           return newValue
         }
    }
}

However I have seen people use :value="data | dataFilter" but you will have to do a little bit of extra work because you are not using the v-model directive.