使用vue写一个音乐播放器
时间: 2024-05-16 14:16:16 浏览: 117
好的,以下是一个简单的音乐播放器示例:
1. 安装依赖
```
npm install vue vue-router vuex axios element-ui --save
```
2. 创建路由和页面组件
在 `src/router/index.js` 中定义路由:
```javascript
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home.vue'
import Player from '@/views/Player.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/player/:id',
name: 'player',
component: Player
}
]
})
```
在 `src/views` 目录中创建 `Home.vue` 和 `Player.vue` 页面组件。
`Home.vue` 组件中展示歌曲列表,点击歌曲可以跳转到对应的 `Player.vue` 组件进行播放。
```html
<template>
<div>
<h1>音乐列表</h1>
<ul>
<li v-for="song in songs" :key="song.id">
<router-link :to="'/player/' + song.id">{{ song.name }}</router-link>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
songs: []
}
},
mounted() {
axios.get('/api/songs').then(res => {
this.songs = res.data
})
}
}
</script>
```
`Player.vue` 组件中展示当前播放的歌曲信息和播放控制按钮。
```html
<template>
<div>
<h1>{{ song.name }}</h1>
<audio ref="audio" :src="song.url"></audio>
<button @click="play">播放</button>
<button @click="pause">暂停</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
song: {}
}
},
mounted() {
axios.get(`/api/songs/${this.$route.params.id}`).then(res => {
this.song = res.data
})
},
methods: {
play() {
this.$refs.audio.play()
},
pause() {
this.$refs.audio.pause()
}
}
}
</script>
```
3. 创建后端接口
在 `server.js` 中创建后端接口,示例中使用 Express 框架和 MongoDB 数据库。
```javascript
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const app = express()
app.use(cors())
app.use(express.json())
mongoose.connect('mongodb://localhost/music', { useNewUrlParser: true })
const Song = mongoose.model('Song', {
name: String,
url: String
})
app.get('/api/songs', async (req, res) => {
const songs = await Song.find()
res.json(songs)
})
app.get('/api/songs/:id', async (req, res) => {
const song = await Song.findById(req.params.id)
res.json(song)
})
app.post('/api/songs', async (req, res) => {
const song = new Song({
name: req.body.name,
url: req.body.url
})
await song.save()
res.json(song)
})
app.listen(3000, () => {
console.log('Server is running at http://localhost:3000')
})
```
4. 配置代理
在 `vue.config.js` 中配置代理,将 `/api` 的请求转发到后端接口。
```javascript
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
}
}
}
```
5. 运行应用
在命令行中执行 `npm run serve` 启动应用,访问 http://localhost:8080 可以看到音乐列表界面。点击歌曲可以播放对应的音乐。
阅读全文
相关推荐


















