如何使用从 API 中获取的数据填写表格?

How to fill a form with fetched data from an API?

我制作了用户信息页面,用户可以更改和更新他们的信息。我想显示数据并使用获取请求数据自动填写表单输入。

<template>
  <div>
    <div class="container">
      <div class="row gutters">
        <div class="col-xl-3 col-lg-3 col-md-12 col-sm-12 col-12">
          <div class="card h-100">
            <div class="card-body">
              <div class="account-settings">
                <div class="user-profile">
                  <div class="user-avatar">
                    <img src="../../assets/people/a2.jpg" alt="Avatar" class="profile_avatar">
                  </div>
                  <h5 class="full_name">B</h5>
                  <h6 class="email">bngu@a.org</h6>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="col-xl-9 col-lg-9 col-md-12 col-sm-12 col-12">
          <div class="card h-100">
            <div class="card-body">
              <div class="row gutters">
                <div class="col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                  <h6 class="mb-2 text-primary">Profil Detayı</h6>
                </div>
                <div class="col-xl-6 col-lg-6 col-md-6 col-sm-6 col-12">
                  <div class="form-group">
                    <label for="first_name">İsim</label>
                    <input type="text" class="form-control" id="first_name" placeholder="İsim" :value="first_name" required :disabled="!isEditable">
                  </div>
                </div>
                <div class="col-xl-6 col-lg-6 col-md-6 col-sm-6 col-12">
                  <div class="form-group">
                    <label for="last_name">Soyisim</label>
                    <input type="text" class="form-control" id="last_name" placeholder="Soyisim" v-model="last_name" :disabled="!isEditable">
                  </div>
                </div>
                <div class="col-xl-6 col-lg-6 col-md-6 col-sm-6 col-12">
                  <div class="form-group">
                    <label for="username">Username</label>
                    <input type="text" class="form-control" id="username" placeholder="Username" :value="username" disabled>
                  </div>
                </div>
                <div class="col-xl-6 col-lg-6 col-md-6 col-sm-6 col-12">
                  <div class="form-group">
                    <label for="email">Email</label>
                    <input type="email" class="form-control" id="email" placeholder="Email" v-model="email" disabled>
                  </div>
                </div>
                <div class="col-xl-6 col-lg-6 col-md-6 col-sm-6 col-12">
                  <div class="form-group">
                    <label for="gsm_number">Telefon</label>
                    <input type="text" class="form-control" id="gsm_number" placeholder="Telefon" v-model="gsm_number" :disabled="!isEditable">
                  </div>
                </div>
                <div class="col-xl-6 col-lg-6 col-md-6 col-sm-6 col-12">
                  <label for="gsm_number">Şifre</label>
                  <b-input-group>
                    <b-form-input type="password" class="form-control" id="password" placeholder="Şifre" v-model="password" :disabled="!isEditable"></b-form-input>
                    <template #append>
                      <b-button v-b-modal.modal-prevent-closing variant="default" @click="passwordModal"><i class="fa fa-pencil-square-o"></i> </b-button>
                      <b-modal
                          id="modal-prevent-closing"
                          ref="modal"
                          title="Şifre Değiştir"
                      >
                        <form ref="form" @submit.stop.prevent="handleSubmit">
                          <b-form-group
                              label="Mevcut Şifre"
                              label-for="password"
                              invalid-feedback="Mevcut şifrenizi giriniz"
                          >
                            <b-form-input type="password" class="form-control" id="password"
                            ></b-form-input>
                          </b-form-group>
                          <b-form-group
                              label="Yeni Şifre"
                              label-for="new_pass"
                              invalid-feedback="Yeni şifrenizi giriniz"
                          >
                            <b-form-input type="password" class="form-control" id="new_pass"
                            ></b-form-input>
                          </b-form-group>
                          <b-form-group
                              label="Yeni Şifre Doğrulama"
                              label-for="new_pass_con"
                              invalid-feedback="Yeni şifrenizi tekrar giriniz"
                          >
                            <b-form-input type="password" class="form-control" id="new_pass_con"
                            ></b-form-input>
                          </b-form-group>
                        </form>
                      </b-modal>
                    </template>
                  </b-input-group>
                </div>
              </div>
                  <div class="inline">
                    <b-button v-if="!isHidden" v-on:click="isHidden = true" variant="default" @click="editProfile"><i class="fa fa-pencil" id="editButton"></i> </b-button>
                    <b-button  variant="default" @click="saveProfile"><i class="fa fa-save" id="saveButton"></i> </b-button>
                  </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

是否可以选择只调用 userinfo 并填写所有输入?或者我应该对我的所有输入(如 first_name、last_name 等)做同样的事情 this.username = res.data 吗?这是我的方法:

<script>

import axios from 'axios'
export default {
  name:'ProfilePage',
  data(){
    return{
      isEditable:false,
      isHidden:false,
      username:"",
      userinfo:[]
    }
  },
  methods:{
    getProfile(){
      if(this.$route.params.id == undefined ||  this.$route.params.id == null){
        axios.get(`/v1/management/update_user/`)
            .then(res=>{console.log(res)
              this.username = res.data

            })
      }else {
        axios.get(`/v1/management/update_user/${this.$route.params.id}`)
            .then(res=>{console.log(res)
              this.username = res.data
            })
      }
    },
    editProfile(){
      this.isEditable = !this.isEditable
    },
    saveProfile(){

    },
    passwordModal(){

    },
    checkResetPassword(){
      if(this.new_pass!== this.new_pass_con){
        this.$toasted.error("Şifreler farklı!"),{
          action: {
            text: 'Kapat',
            onClick: (e, toastObject) => {
              toastObject.text("").goAway(10);
            }
          }
        }

      }else {
        this.$toasted.success("İşlem başarılı!"),{
          action: {
            text: 'Kapat',
            onClick: (e, toastObject) => {
              toastObject.text("").goAway(10);
            }
          }
        }
      }
    }
  },
  mounted() {
    this.getProfile()
  }
}


</script>

更新

<template>
  <div>
    <div class="form-group">
      <label for="username">Username</label>
      <input id="username" type="text" class="form-control" placeholder="Username" :value="userinfo.username" disabled>
      <input id="email" type="text" class="form-control" placeholder="email" :value="userinfo.email" disabled>
      <input id="website" type="text" class="form-control" placeholder="website" :value="userinfo.website" disabled>
      <button @click="fetchUser">fetch some user</button>
      <p>Actual user info object: <pre>{{ userinfo }}</pre></p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userinfo: {}
    }
  },
  methods: {
    async fetchUser() {
      const response = await fetch('https://jsonplaceholder.typicode.com/users/1')
      const data = await response.json()
      this.userinfo = data
    },
  }
}
</script>

这种基本代码应该完全可以工作

<template>
  <div>
    <div class="form-group">
      <label for="username">Username</label>
      <input type="text" class="form-control" id="username" placeholder="Username" :value="username" disabled>
      <button @click="fetchUser">fetch some user</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: 'nick'
    }
  },
  methods: {
    async fetchUser() {
      const response = await fetch('https://jsonplaceholder.typicode.com/users/1')
      const data = await response.json()
      this.username = data.username
    },
  }
}
</script>

这里是a playground

您可以使用 v-model 将数据绑定到表单字段中。出于演示目的而不是 v-for,我直接绑定基于索引的值。

工作演示:

const app = new Vue({
  el: '#app',
  data() {
    return {
      userInfo: []
    }
  },
  mounted() {
    this.getProfile();
  },
  methods: {
    // Just for demo I am directly assigning the mock response in userInfo array. You can replace that with API call response.
    getProfile() {
        this.userInfo = [{
        username: 'alpha'
      }]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  UserName : <input type="text" v-model="userInfo[0].username">
</div>