vue2.0开发web音乐app

作者 新城 日期 2017-10-27
vue2.0开发web音乐app

vue-cil脚手架安装

1
2
3
4
5
6
7
vue init webpack vue-music  //初始化脚手架工具

cd vue-music // 进入项目文件夹

npm install // 加载依赖

npm run dev // 启动项目

基本目录结构


vue-music

- build
-config
-node_modules
-src
    -api  //放置与后端请求相关
    -common  // 公共字体文件 图片 css js
    -components  //组件目录
    -router  // 路由
    -store   // vuex
    app.vue
    main.js
-static

common解析


common
-fonts
-images
-js
-stylus
-base.stul // 定义html body 引入@import “variable.styl”
-icon.styl // 字体图标生成
-index.styl // 向外面暴露styl 1.reset 2.base 3.icon 没有引用mixin
-mixin.styl // 公共函数
-reset.styl // 复位
-variable.styl // 定义全局字体颜色


多会用到mixin多会引用
添加依赖
打开package文件
1
2
3
4
5
6
7
// dependencies中添加  的依赖打包的时候会进行打包发布
"babel-runtime": "^6.0.0",
"fastclick": "^1.0.6"
// devDependencies中添加的依赖不进行打包发布 只在编译的时候依赖
"babel-polyfill": "^6.2.0"
"stylus": "^0.54.5",
"stylus-loader": "^3.0.1",

在main.js中
import ‘babel-polyfill’
import fastclick from “fastclick”

fastclick.attach(document.body) // 阻止移动端300ms延迟

路由设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 路由设置在router文夹下面
Vue.use(Router) // 注册

export default new Router({
routes: [
{
path: '/',
redirect: '/recommend' // 表示重定向
},
{
path: '/recommend',
component: recommend
}
]
})
//在main.js中导入router 挂载到vue实例上面
new Vue({
el: '#app',
router, // 将路由挂载到vue实例上
render: h => h(App)
})

VUE 使用jsonp跨域请求封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import originJsonp from 'jsonp'

export default function jsonp(url, data, option) {
url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)

return new Promise((resolve, reject) => {
originJsonp(url, option, (err, data) => {
if (!err) {
resolve(data)
} else {
reject(err)
}
})
})
}

export function param(data) {
let url = ''
for (var k in data) {
let value = data[k] !== undefined ? data[k] : ''
url += '&' + k + '=' + encodeURIComponent(value)
}
return url ? url.substring(1) : ''
}

封装好jsonp之后 在api目录下去使用jsonp请求数据
1.api文件夹新建recommend.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import jsonp from '@/common/js/jsonp'
import {commonParams, options} from './config'
// import axios from 'axios'

// 获取推荐轮播图
export function getRecommend () {
const url = 'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg'

const data = Object.assign({}, commonParams, {
platform: 'h5',
uin: 0,
needNewCode: 1
})

return jsonp(url, data, options)
}

ES6新语法 Object.assign方法用来合并对象
2.api文件夹新建config.js
作用:封装 一些全局变量

1
2
3
4
5
6
7
8
9
10
11
12
export const commonParams = {
g_tk: 1928093487,
inCharset: 'utf-8',
outCharset: 'utf-8',
notice: 0,
format: 'jsonp'
}

export const options = {
param: 'jsonpCallback'
}
export const ERR_OK = 0