[Vuejs]-Vue change value and text on axios post success or fail

0👍

You can tie the API return to data props, bind the input value to those data props, and use v-if to determine if they should be shown. Example below – please let me know if this solves your issue or if I’m misunderstanding what you’re after.

I had to use a ‘pseudo example’, so it’s not 1:1 with your code, but this should be enough to get the point across.

[CodePen mirror]

new Vue({
  el: "#app",
  data: {
    id: "",
    title: "",
    error: ""
  },
  methods: {
    clearResults() {
      this.id = "";
      this.title = "";
      this.error = "";
    },
    simulateError() {
      this.clearResults();
      this.error = "Something went wrong!"
    },
    getData() {
      this.clearResults();
      var vm = this;
      axios
        .get("https://jsonplaceholder.typicode.com/todos/1")
        .then(function(response) {
          if (response.data.id && response.data.title) {
            vm.id = response.data.id;
            vm.title = response.data.title;
          }
        })
        .catch(function(error) {
          vm.error = error;
        });
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>

<div id="app">
  <div>
    <div>
      <button @click="getData" style="color:green;">Click to load data from api</button>
      <button @click="simulateError" style="color:red;">Click to simulate error</button>
    </div>
    <div style="margin-top:10px;">
      <input v-if="id != '' && title != ''" :name="title" :value="id" />
    </div>
    <div>
      <p v-if="error != ''" style="color:red;">{{ error }}</p>
    </div>
  </div>
</div>

0👍

Solved it in the end, and i just needed to change one line of the code:

axios.post( this.post_url,
  formData,
   {
       headers: {
         'Content-Type': 'multipart/form-data'
       }
    }
 ).then(function(response) {
   this.file = response.data;
}

From this.file.id = response.data.id to this.file = response.data

And this would work:

<div v-if="file.id > 0">
    <input type="hidden" :name="input_name" :id="input_name" :value="file.id" />
</div>

Leave a comment