1、使用Vue开发的时候,肯定要使用到ajax去服务端请求数据。这个时候就需要用到AJAX发送请求到服务端,Vue项目内置了对http的支持,
到项目目录下,安装vue-resource
npm install vue-resource
2、使用http请求执行需要先添加对应用到的类库,找到src目录下的 main.js ,添加一下内容
// 引入http请求相关类库
import VueResource from 'vue-resource'
//使用http请求相关类库
Vue.use(VueResource)
// 确保post请求不会被转换为 options 请求
Vue.http.options.emulateJSON = true
完整文件内容如下
// 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'
// 引入http请求相关类库
import VueResource from 'vue-resource'
Vue.config.productionTip = false
//使用http请求相关类库
Vue.use(VueResource)
// 确保post请求不会被转换为 options 请求
Vue.http.options.emulateJSON = true
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
3、设置代理服务器,因为JS是无法跨越请求的,所以我们需要设置 Vuejs的 开发服务器配置,找到config目录下的index.js
// 这块内容设置代码
proxyTable: {
// 请求带api的全部按照一下规则处理
'/api':{
// 转发到该域名
target: 'http://1908api.phpclub.top',
// 开启代理
changeOrigin: true,
pathRewrite: {
'^/api' : ''
}
}
},
// 这块内容设置代码
完整内容如下
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
// 这块内容设置代码
proxyTable: {
// 请求带api的全部按照一下规则处理
'/api':{
// 转发到该域名
target: 'http://api.phpclub.top',
// 开启代理
changeOrigin: true,
pathRewrite: {
'^/api' : ''
}
}
},
// 这块内容设置代码
// Various Dev Server settings
// 监听的端口好
host: '0.0.0.0', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, 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-
// Use Eslint Loader?
// If true, your code will be linted during bundling and
// linting errors and warnings will be shown in the console.
useEslint: true,
// If true, eslint errors and warnings will also be shown in the error overlay
// in the browser.
showEslintErrorsInOverlay: false,
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
设置完代理之后,会自动把 http://locahost:8080/api的请求转发到http://api.phpclub.top这个域名下。
4、设置完成之后,重启下Vue项目
5、新建一个页面添加一个按钮
//HTML
<input @click="sendAjax()" type="button" value="发送ajax"/>
6、在vuejs代码的methods中添加 sendAjax 方法
//JS 发送一个POST请求,提交数据格式为JSON
sendAjax: function () {
this.$http.post('/api/user/login', {user_name: 'zhangsan'}).then((response) => {
console.log(response)
}, (error) => {
console.log(error)
})
},
// then是JS promise的相关写法,可以参考
// then( 成功(){} ,失败(){} )