Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set input value by VueJS and mixing the content of value

Tags:

vue.js

vuejs2

I try this:

<input type="text"
    name="username"
    v-model="user.name"
    :value="'The user name is: '+user.name">

Is possible somehow to show in the input filed is "The user name is: John Doe" ?

Or I need definitely use a computed value in this case?

like image 810
netdjw Avatar asked Aug 31 '25 18:08

netdjw


2 Answers

The options seem to be to either bind directly to the value, instead of a v-model, or to created a computed property and v-model to that:

https://codepen.io/aprouja1/pen/jwxagE

new Vue({
  el:'#app',
  data(){
    return{
      user:{
        name:'Bob'
      }
    }
  },
  computed:{
    nameString(){
      return `The user name is: ${this.user.name}`
    }
  }
})
like image 152
aprouja1 Avatar answered Sep 02 '25 13:09

aprouja1


What you're asking for (I think) it a little bit confusing because you're basically saying you want the textbox to contain text like "The user name is: Bob" but you want user.name to equal "Bob" even after the user edits the textbox value to some text which may not even begin with "The user name is: ".

Realistically the text "The user name is: " should not be in the textbox at all, it should be a <label>:

  <label>The user name is:</label>
  <input type="text" name="username" v-model="user.name">

You can also use CSS to create your own custom "input" element which contains a <label> and an <input> element with all styles removed so it looks like the text "The user name is: " is part of the editable text but actually isn't.

like image 21
Decade Moon Avatar answered Sep 02 '25 14:09

Decade Moon