使用vue全家桶搭建购物网站
A Vue.js project
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
For detailed explanation on how things work, checkout the guide and docs for vue-loader.
npm install --save-dev axios
npm install --save-dev vue-axios
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = 'http://localhost:8081/';
axios.interceptors.request.use((config) => {
if(config.method === 'post'){
config.data = JSON.stringify(config.data);
}
return config;
}, (error) => {
return Promise.reject(error);
});
# get
this.axios.get(uri
).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
})
# post
this.axios.post(uri,{data: data
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
})
# 省略PUT,DELETE
npm install --save-dev json-server
在build/dev-server.js中配置
# json-server数据测试
const jsonServer = require('json-server')
const apiServer = jsonServer.create()
# 配置json数据源为根目录下的db.json
const apiRouter = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()
apiServer.use(middlewares)
apiServer.use(apiRouter)
# 监听数据源端口8081
apiServer.listen("8081", () => {
console.log('JSON Server is running')
})
var apiRouter = express.Router()
var fs = require('fs')
apiRouter.route('/:apiName')
.all(function (req, res) {
fs.readFile('./db.json', 'utf8', function (err, data) {
if (err) throw err
var data = JSON.parse(data)
if (data[req.params.apiName]) {
res.json(data[req.params.apiName])
}
else {
res.send('no such api name')
}
})
})
apiServer.use(middlewares)
apiServer.use(apiRouter)
//数据源端口8081
apiServer.listen(port + 1, (err) => {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:' + (port + 1) + '\n')
})
在根目录下编写db.json数据源 db.json例:
{
"news": [
{
"id": 1,
"title": "英美会谈",
"url": "http://starcraft.com"
},
{
"id": 2,
"title": "G20峰会",
"url": "http://warcraft.com"
},
{
"id": 3,
"title": "高考状元",
"url": "http://overwatch.com"
},
{
"id": 4,
"title": "状元采访",
"url": "http://hearstone.com"
}
]
}
注:默认情况下,异步请求uri为json数据的key值,如上述数据url为http://localhost:8081/news
npm run dev # 启动
####github地址:https://github.com/vuejs/awesome-vue