本文轉載自:http://www.javashuo.com/article/p-akjpvqjo-bx.htmlcss
vue實現ajax獲取後臺數據是經過vue-resource,首先經過npm安裝vue-resourcehtml
npm install vue-resource --save
安裝完成之後,把vue-resource引入到main.js文件中前端
src/main.jsvue
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import VueResource from 'vue-resource' import Layout from './components/layout' Vue.use(VueResource); /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<Layout/>', components: { Layout } })
把vue-resource引入項目之後,就能夠在任何組件裏面直接用了webpack
<template> <div class="index-wrap"> <div class="index-left"> <div class="index-left-block lastest-news"> <h2>最新消息</h2> <ul> <li v-for="news in newsList"> <a :href="news.url" class="new-item">{{news.title}}</a> </li> </ul> </div> </div> <div class="index-right"> </div> </div> </template> <script type="text/ecmascript-6"> export default{ created(){ this.$http.get('api/getNewsList').then((res)=>{ //可用post請求,this.$http.post('api/getNewsList',{'userId':123}) console.log(res.data); this.newsList=res.data; console.log( this.newsList); },(err)=>{ console.log(err); }); }, data(){ return { newsList:[], } } } </script> <style scoped> .index-wrap{ width: 1200px; margin: 0 auto; overflow: hidden; background: blue; } .index-left{ float: left; width: 300px; text-align: left; background: red; } .index-right { float: left; width: 900px; } .index-left-block{ margin: 15px; background: #fff; box-shadow: 0 0 1px #ddd; } .index-left-block .hr { margin-bottom: 20px; border-bottom: 1px solid #ddd; } .index-left-block h2 { background: #4fc08d; color: #fff; padding: 10px 15px; margin-bottom: 20px; } .index-left-block h3 { padding: 0 15px 5px 15px; font-weight: bold; color: #222; } .index-left-block ul { padding: 10px 15px; } .index-left-block li { padding: 5px; } .hot-tag{ background: red; color:#fff; font-size: 10px; border-radius: 10px; } </style>
上面這個就是用vue-resource來進行數據請求的大致流程,做爲前端,在開發的過程,遇到這種調用後端接口調試起來仍是很麻煩的,咱們要找後端的一個服務器,而後關聯起來 ,或者把前端代碼放上去,這樣都是挺麻煩的,解決的辦法就是前端放mock data,主要有兩種方式:git
(1)json-server模擬數據github
使用json-server這個工具,能夠虛構出後端接口對應的數據,而後在項目裏發送特定的請求,就能夠發請求拿到模擬的數據,首先npm安裝web
npm install json-server --save
而後在build/webpack.dev.conf.js中進行配置,參考json-serverajax
'use strict' const utils = require('./utils') const webpack = require('webpack') const config = require('../config') const merge = require('webpack-merge') const baseWebpackConfig = require('./webpack.base.conf') const HtmlWebpackPlugin = require('html-webpack-plugin') const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') const portfinder = require('portfinder') const devWebpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool, // these devServer options should be customized in /config/index.js devServer: { clientLogLevel: 'warning', historyApiFallback: true, hot: true, host: process.env.HOST || config.dev.host, port: process.env.PORT || config.dev.port, open: config.dev.autoOpenBrowser, overlay: config.dev.errorOverlay ? { warnings: false, errors: true, } : false, publicPath: config.dev.assetsPublicPath, proxy: config.dev.proxyTable, quiet: true, // necessary for FriendlyErrorsPlugin watchOptions: { poll: config.dev.poll, } }, plugins: [ new webpack.DefinePlugin({ 'process.env': require('../config/dev.env') }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true }), ] }) //這裏是json-server配置信息 // json-server.js const jsonServer = require('json-server') const apiServer = jsonServer.create() const apiRouter = jsonServer.router('db.json') //數據關聯server,db.json與index.html同級 const middlewares = jsonServer.defaults() apiServer.use(middlewares) apiServer.use('/api',apiRouter) apiServer.listen(3000, () => { //監聽端口 console.log('JSON Server is running') }) module.exports = new Promise((resolve, reject) => { portfinder.basePort = process.env.PORT || config.dev.port portfinder.getPort((err, port) => { if (err) { reject(err) } else { // publish the new Port, necessary for e2e tests process.env.PORT = port // add port to devServer config devWebpackConfig.devServer.port = port // Add FriendlyErrorsPlugin devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ compilationSuccessInfo: { messages: [`Your application is running here: http://${config.dev.host}:${port}`], }, onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined })) resolve(devWebpackConfig) } }) })
配置完成之後,npm run dev 啓動,瀏覽器輸入localhost:3000,出現以下圖,說明配置成功express
那麼如今還有一個問題,咱們代碼的服務端接口是8080,json-server的服務端端口是3000,因爲瀏覽器的同源策略問題,這樣請求會存在一個跨域問題,因此這裏要作一個服務端代理的配置,配置build/index.js中的proxyTable:
host: 'localhost', // can be overwritten by process.env.HOST port: 8080, // can be overwritten by process.env.HOST, if port is in use, a free one will be determined autoOpenBrowser: false, errorOverlay: true, notifyOnErrors: true, poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions- proxyTable:{ '/api/':'http://localhost:3000/' },
這樣就能夠在localhost:8080下訪問接口了
(2)express啓動數據服務
在實際開發中,發現json-server只能用於get請求,不能進行post請求,在網上找的另一種方法,express既能用於get請求,又能用於post請求,下面說一下express啓動服務的配置方法:
'use strict' const utils = require('./utils') const webpack = require('webpack') var express = require('express') const config = require('../config') const merge = require('webpack-merge') const baseWebpackConfig = require('./webpack.base.conf') const HtmlWebpackPlugin = require('html-webpack-plugin') const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin') const portfinder = require('portfinder') const devWebpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) }, // cheap-module-eval-source-map is faster for development devtool: config.dev.devtool, // these devServer options should be customized in /config/index.js devServer: { clientLogLevel: 'warning', historyApiFallback: true, hot: true, host: process.env.HOST || config.dev.host, port: process.env.PORT || config.dev.port, open: config.dev.autoOpenBrowser, overlay: config.dev.errorOverlay ? { warnings: false, errors: true, } : false, publicPath: config.dev.assetsPublicPath, proxy: config.dev.proxyTable, quiet: true, // necessary for FriendlyErrorsPlugin watchOptions: { poll: config.dev.poll, } }, plugins: [ new webpack.DefinePlugin({ 'process.env': require('../config/dev.env') }), new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update. new webpack.NoEmitOnErrorsPlugin(), // https://github.com/ampedandwired/html-webpack-plugin new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true }), ] }) // json-server.js //const jsonServer = require('json-server') //const apiServer = jsonServer.create() //const apiRouter = jsonServer.router('db.json') //const middlewares = jsonServer.defaults() // //apiServer.use(middlewares) //apiServer.use('/api',apiRouter) //apiServer.listen(3000, () => { // console.log('JSON Server is running') //}) //express 配置server var apiServer = express() var bodyParser = require('body-parser') apiServer.use(bodyParser.urlencoded({ extended: true })) apiServer.use(bodyParser.json()) 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('/api', apiRouter); apiServer.listen(3000, function (err) { if (err) { console.log(err) return } console.log('Listening at http://localhost:' + 3000 + '\n') }) module.exports = new Promise((resolve, reject) => { portfinder.basePort = process.env.PORT || config.dev.port portfinder.getPort((err, port) => { if (err) { reject(err) } else { // publish the new Port, necessary for e2e tests process.env.PORT = port // add port to devServer config devWebpackConfig.devServer.port = port // Add FriendlyErrorsPlugin devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ compilationSuccessInfo: { messages: [`Your application is running here: http://${config.dev.host}:${port}`], }, onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined })) resolve(devWebpackConfig) } }) })
在瀏覽器中輸入接口地址,以下: