How to keep part of a v-model(string) fixed in an input with Vuejs!

Asked

Viewed 102 times

-1

I have an input text with its respective model, but I need a part of this value to be fixed, for example: /static/download.jpg the idea is that the user can only change the text that is after /static/.. keeping this part fixed on the model.

I tended to implement a rule in @input and @change but it didn’t go very well.. Any suggestions?

Thank you!

Edit: I tried an implementation here with the event @change in the input.. more at times it includes more than once the / after the /static/, follows the code passage below!

var initialModel1 = '/static/teste.jpg';
var initialModel2 = 'teste.jpg';
var initialModel3 = '';

function test(model) {

  if (model.indexOf('/static/') === 0) {
    model = `/static/${model.substr(8)}`;

    console.log(model)
    return;
  }

  if (model !== '') {
    model = `/static/${model}`;

    console.log(model)
    return;
  }

  model = `/static/`;
  console.log(model)
}

test(initialModel1);
test(initialModel2);
test(initialModel3);

1 answer

1

You should use observers for this, see:

html:

...
<input type="text" v-model="input">
...

vuejs:

...
export default {
    data(){
        return {
            ...
            input:'/static/'
        }
    },
    watch:{
        input: function(value){
            return '/static/'.value
        }
    }
}

Obviously my example is very thick and there are better ways to do as for example prefix this with a type of bootstrap inputgroup for example and take only what the user type and assume in the backend that what is inserted enters after the path... depends a lot on the result final. As you were generic in doubt I responded more generally to illustrate the concept.

This link here can be useful to you:

https://br.vuejs.org/v2/guide/computed.html#Computed Data-vs-Observers

Browser other questions tagged

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