基于Vue.js实现文本编辑后提交并更新数据库answer.name列内容的技术咨询
Hey there! Let's sort this out step by step—you're mixing vanilla JS DOM manipulation with Vue's reactive system, which is why things feel stuck. Vue works best when you lean into its data-driven approach instead of directly touching the DOM. Here's how to properly submit your edited answer and update the database:
1. Fix your template to use Vue's native bindings
First, ditch the onclick handler and direct DOM calls. Use Vue's @click event binding instead, and let Vue manage the input value via v-model like you already started:
<input v-model="answer.name" placeholder="Edit the answer here"> <button @click="submitUpdatedAnswer">Save Answer</button>
2. Add the submit logic in your Vue component
In your component's script section, define a method that handles sending the updated data to your backend API. We'll use async/await for clean async code, and a library like axios for HTTP requests (you can use fetch too if you prefer):
export default { data() { return { // Initialize with your existing answer data (load this from backend first for edits) answer: { id: 1, // Replace with your actual answer ID name: '' } }; }, methods: { async submitUpdatedAnswer() { try { // Send the updated answer to your backend API endpoint // Use PUT if updating an existing record, POST if creating a new one const response = await axios.put(`/api/answers/${this.answer.id}`, { name: this.answer.name }); // Handle success: show feedback to the user alert('Answer updated successfully!'); // Optional: Refresh data or navigate to another page } catch (error) { // Handle errors: log and inform the user console.error('Update failed:', error); alert('Oops, failed to update the answer. Please try again.'); } } }, // If you're editing an existing answer, load its data when the component mounts async mounted() { // Fetch the current answer data from your backend const response = await axios.get(`/api/answers/${this.answer.id}`); this.answer = response.data; } };
3. Backend: Create an endpoint to update the database
You'll need a backend API route that receives the updated answer data and writes it to your database. Here's a quick example using Node.js/Express and Sequelize (adjust to match your stack):
// Backend example (Node.js/Express) app.put('/api/answers/:id', async (req, res) => { try { const answerId = req.params.id; const newAnswerText = req.body.name; // Update the `name` column in your `answer` table await Answer.update( { name: newAnswerText }, { where: { id: answerId } } ); res.status(200).json({ message: 'Answer updated successfully' }); } catch (error) { res.status(500).json({ error: 'Failed to update answer in database' }); } });
Key Notes
- Forget direct DOM manipulation: Vue's reactive system keeps your data and UI in sync. Using
document.getElementByIdbypasses this, leading to inconsistent state. - Validate input: Add checks for empty text or invalid content before sending the request to the backend.
- Loading states: Consider adding a loading spinner to the button while the request is in flight, so users know something's happening.
内容的提问来源于stack exchange,提问作者Marcello D'Ambrosio

