vue点击按钮获取当前时间并传向后端
时间: 2023-10-18 15:11:43 浏览: 72
在 Vue 中,可以使用 `new Date()` 来获取当前时间。然后,可以将时间作为参数传递给后端接口。假设你使用的是 Axios 来发送请求,可以按照以下步骤进行操作:
1. 在 Vue 组件中定义一个时间变量,用于存储当前时间:
```
data() {
return {
currentTime: ''
}
}
```
2. 在模板中添加一个按钮,并绑定一个点击事件:
```
<button @click="sendTime">获取当前时间</button>
```
3. 在 `sendTime` 方法中获取当前时间,并发送请求:
```
methods: {
sendTime() {
const currentTime = new Date()
axios.post('/api/saveTime', { time: currentTime })
.then(response => {
// 处理响应
})
.catch(error => {
// 处理错误
})
}
}
```
4. 在后端接口中接收时间参数,并进行处理:
```
app.post('/api/saveTime', (req, res) => {
const time = req.body.time
// 处理时间
})
```
注意,上述代码中的 `/api/saveTime` 是一个示例接口地址,你需要将它替换为你自己的后端接口地址。另外,还需要在组件中引入 Axios,例如:
```
import axios from 'axios'
```