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

input同时使用v-model与:value报错,需实现API数据展示与修改提交

解决Vue中Input同时使用v-model和:value的冲突问题

嘿,我一眼就看出问题所在啦——你在同一个<input>上同时用了v-model和:value,这俩可是天生的“冤家”,一起用肯定会触发冲突报错的!

为什么会报错?

v-model本质是Vue的语法糖,它等价于同时绑定:value和@input事件:

<input :value="titre" @input="titre = $event.target.value">

你手动再加一个:value="posts['titre_panneau']",等于让Vue同时收到两个不同的“值绑定指令”,它根本不知道该听哪一个,自然会抛出错误。

解决方案:只保留v-model,通过初始化赋值实现需求

你要的效果是“先展示API返回值,再支持修改后提交”,只需要两步就能搞定:

1. 初始化数据并在API请求后赋值

在组件的data(Options API)或者ref(Composition API)里定义titre变量,等GET请求拿到posts数据后,把posts.titre_panneau赋值给titre。

2. 模板里只保留v-model绑定

去掉:value,让v-model全权负责值的展示和更新。


完整代码示例(Options API)

<template>
  <div>
    <!-- 只保留v-model即可 -->
    <input type="text" class="form-control" v-model="titre">
    <button @click="submitUpdate">提交修改</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      titre: '', // 初始化titre为空
      posts: {} // 存储API返回的完整数据
    }
  },
  mounted() {
    // 页面加载时发起GET请求获取数据
    this.fetchPosts()
  },
  methods: {
    async fetchPosts() {
      // 替换成你的实际API地址
      const res = await fetch('/api/your-post-endpoint')
      this.posts = await res.json()
      // 将API返回的titre_panneau赋值给titre,input会自动显示这个值
      this.titre = this.posts.titre_panneau
    },
    async submitUpdate() {
      // 发起PUT请求提交修改后的titre
      await fetch('/api/your-post-endpoint', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ titre_panneau: this.titre })
      })
      // 提交后的逻辑,比如提示成功或重新拉取数据
      alert('修改已提交!')
      this.fetchPosts()
    }
  }
}
</script>

如果你用Composition API

<template>
  <input type="text" class="form-control" v-model="titre">
  <button @click="submitUpdate">提交修改</button>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const titre = ref('')
const posts = ref({})

const fetchPosts = async () => {
  const res = await fetch('/api/your-post-endpoint')
  posts.value = await res.json()
  titre.value = posts.value.titre_panneau
}

const submitUpdate = async () => {
  await fetch('/api/your-post-endpoint', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ titre_panneau: titre.value })
  })
  alert('修改成功!')
  fetchPosts()
}

onMounted(fetchPosts)
</script>

这样修改后,input会先显示API返回的titre_panneau值,你修改输入框内容时titre变量会自动更新,提交PUT请求时直接用这个变量的值就完全符合你的需求啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:34:06