Daily Skill#
Preface#
A friend of mine recently encountered a problem while using Vue.
At that time, I didn't have time to organize the code because of the final defense. Today, while organizing my computer files, I happened to see the code I sent to my friend. I will organize the ideas and code and write an article to hopefully help more people.
Requirements#
Implement a form where data can be entered and displayed in a table after clicking the submit button.
Requirements Analysis#
Bind the data from the form to the table and display the data in the table after clicking the submit button.
The submitForm method can be used to handle form submission logic.
Data can be bound bidirectionally using v-model.
The following is the code implementation, for more details, please see the code analysis below.
Code Implementation#
<!-- Import Vue JavaScript file -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- Define the HTML structure of the form -->
<div id="app">
<form>
<label>Username:</label>
<input type="text" v-model="username" /><br>
<label>Password:</label>
<input type="password" v-model="password" /><br>
<button type="submit" @click.prevent="submitForm">Register</button>
</form>
<!-- Define the form for displaying data after submission -->
<div v-if="submitted">
<label>Username:</label>
<span>{{ username }}</span><br>
<label>Password:</label>
<span>{{ password }}</span><br>
</div>
</div>
<!-- Define Vue instance and implement data binding -->
<script>
new Vue({
el: '#app',
data: {
username: '',
password: '',
submitted: false
},
methods: {
submitForm() {
// Update the submitted state and display the username and password in the form below when the form is submitted
this.submitted = true;
}
}
});
</script>
Code Analysis#
v-model
is a directive in Vue.js used to achieve two-way data binding.
In this code, we use the v-model
directive to bind the input fields in the form to the data in the Vue instance. For example, when content is entered in the username input field in the form, the value of the username
property in the Vue instance will also be updated. Conversely, if the value of the username
property is modified in the Vue instance, the content in the username input field in the form will also be updated.
This way, we can use a unified data model in the Vue instance to manage the data in the form and achieve two-way binding of the form data.
In addition, in this code, we define a submitted
state with an initial value of false
. After the form is submitted, we set the submitted
state to true
.
The purpose of this state is to control the display/hide state of the data display form after the form is submitted. Specifically, we use the Vue directive v-if
to determine whether to display the data display form based on the value of the submitted
state.
When the submitted
state is true
, the data display form will be displayed; otherwise, when the submitted
state is false
.