You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue.js中设置输入组件初始值并获取修改后的值?

Solution for Setting Initial Values and Retrieving Updated Inputs in Vue

Let's refactor your component to use Vue's reactive data system and v-model—this is the cleanest, most idiomatic way to handle form inputs in Vue, and it eliminates the need to manually manipulate the DOM for value handling.

Step 1: Update the Template with Two-Way Binding

Replace your static inputs with v-model bindings to reactive data properties. This will automatically sync initial values and keep your data up-to-date as users type.

<template>
  <div class="editUserInfo">
    <input type="text" v-model="userInfo.name" placeholder="Full Name">
    <input type="text" v-model="userInfo.username" placeholder="Username">
    <input type="text" v-model="userInfo.email" placeholder="Email Address">
    <button @click.prevent="updateInfo">Update</button>
  </div>
</template>

Step 2: Set Up Reactive Data and the Update Method

In the script section, define a reactive userInfo object to hold your initial values. The updateInfo method can then directly access the latest input values from this object.

<script>
export default {
  data() {
    return {
      tokenExists: true, // Keep your existing token check here
      userInfo: {
        name: "Andres Concha", // Replace with your initial name value
        username: "andres_c", // Replace with initial username
        email: "andres@example.com" // Replace with initial email
      }
    };
  },
  methods: {
    updateInfo() {
      // Grab the latest values directly from the reactive userInfo object
      const updatedUserData = { ...this.userInfo };
      
      // Log the values to verify (replace with your API call or logic)
      console.log("Updated User Data:", updatedUserData);
      
      // Example API call (uncomment and adjust as needed):
      // axios.put('/api/user/profile', updatedUserData, {
      //   headers: { Authorization: `Bearer ${yourAuthToken}` }
      // })
      // .then(res => console.log("Profile updated successfully!"))
      // .catch(err => console.error("Update failed:", err));
    }
  },
  // Optional: Fetch initial values from an API when the component loads
  mounted() {
    // Example: Load user data from backend on component mount
    // axios.get('/api/user/profile', {
    //   headers: { Authorization: `Bearer ${yourAuthToken}` }
    // })
    // .then(res => {
    //   this.userInfo = res.data; // Overwrite initial values with fetched data
    // })
    // .catch(err => console.error("Failed to load user data:", err));
  }
};
</script>

Key Notes:

  • v-model: Creates a two-way binding between inputs and your reactive data. Any change to an input updates userInfo, and any change to userInfo updates the input—no manual DOM queries needed.
  • Reactive Data: Vue automatically tracks changes to userInfo, so you’ll always have the latest input values available in your methods.
  • Avoid Direct DOM Manipulation: Using document.getElementById to get/set values bypasses Vue’s reactivity system, leading to potential inconsistencies and harder-to-maintain code. v-model is the Vue-recommended approach.

内容的提问来源于stack exchange,提问作者Andres Concha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:56:29