How to load and update from the same input? (VUEJS)

Viewed 455

Right now i show the data in a span tag, and the input to update it

Its possible to load data from api, load it into a input and then update the input to send it back with the new information?, which way are the best approachs?

    <input v-model='name'> // see john and add john doe
    data(){
    return{
     name:''
    }},
    created(){
     this.data()
     },
    methods:{
    updateData(){
     // send the new name value to /updatename api
    },
    data(){
     this.name = api // john its the value
    }}
3 Answers

You could add a name watcher. It will run specified code every time the value of name changes:

<input v-model='name'>
data () {
  return {
    name: ''
  }  
},
watch: {
  name (value) {
    console.log(this.name)
  }
},
methods: {
  setAPIData () {
    this.name = 'API DATA'
  }
}

It's not very clear what you are looking for. what I could understand that you want to show the user current value(name) and let them update the value, to do that parsing the current value from an api and binding it to the input would be better choice.

template:

<input v-model="name">

script:

module export{
    data(){
        return {
            name: ''
        }
    },
    created(){
      // parse current value for name using an api
      this.name = parsed_name
    },
    methods:{
       submit(){
           // on submit update name using an api
           // current value this.name
       }
    }
}

Yes it is possible, first you need to load your data from server and put it into your name property, this made at created lifecycle hook, then after input event you need method to send your data back to server.

<input v-model='name' @submit="setData()">

data(){
 return{
  name:''
 }},
async created() {
 await getData();
},
methods:{
 async getData(){
  this.name = await getApiFunction();
 }
 async setData(){
  await setApiFunction(this.name);
 }
}
Related