我是Vue JS的新手。如何在不重新加载页面的情况下将表单数据发送到Node API,以及如何在成功发送数据的情况下放置动画脚本?
我添加了Vue Axios CDN
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.0"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
这是我的包含实现的HTML表单
<form class="" id="contactform" @submit="contactForm">
<div class="row">
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
<input id="icon_prefix" type="text" class="validate" v-model="name" required>
<label for="icon_prefix">Your name</label>
</div>
<div class="input-field">
<i class="material-icons prefix">phone</i>
<input id="icon_telephone" type="tel" class="validate input-phone" v-model="phone" required>
<label for="icon_telephone">Your phone number</label>
<span class="helper-text" data-error="wrong" data-success="right">Eg.:</span>
</div>
<div class="input-field">
<i class="material-icons prefix">email</i>
<input id="icon_email" type="email" class="validate" v-model="email" required>
<label for="icon_email">Your email</label>
</div>
<div class="input-field message-sect">
<i class="material-icons prefix">message</i>
<button class="sendmessage transparent"><i class="material-icons">send</i></button>
<textarea id="textarea1" class="materialize-textarea" v-model="message"></textarea>
<label for="textarea1">Your message</label>
</div>
<p class="text-secondary">We will call you soon!</p>
<a class="call-now" href="">CALL NOW</a>
<div class="follow-sect">
</div>
</div>
</form>
这是我的Vue代码。而且它正在加载页面,而不是向后端发送数据。
new Vue.Mail({
methods: {
...mapActions({
sendMail: 'sendMail'
})
},
actions: { // actions store methods
// action (context)
sendMail: function () {
axios
.post('http://localhost:80/mail', {
name: '' + this.data.name,
phone: '' + this.data.phone,
email: '' + this.data.email,
message: '' + this.data.message
})
}
},
mutations: {
}
})
这是我的Express JS API,用于处理所有这些相关数据
app.post('/mail', function (req, res) {
db.query('INSERT INTO mail (`name`, `phone`, `email`, `message`, `date_time`) VALUES (?, ?, ?, ?, NOW())', [req.body.name, req.body.phone, req.body.email, req.body.message], function(error, results) {
if (error) throw error;
// res.send(results);
});
});