一、安裝vue-resource插件
cnpm install vue-resource --save
在根目錄下的package.json檢查一下插件的版本
在rourer-index.js下引入文件
import Resource from 'vue-resource'Vue.use(Resource)
引入vue-resource后,可以基于全局的Vue對象使用http,也可以基于某個Vue實例使用http 參考鏈接
二、安裝axios插件
cnpm install --save axios
在后臺服務文件(server.js)中引入
var axios = require('axios')
新建一個公共Js文件,用于存放httpserver
import axios from 'axios' // 引入axios插件export function getHttp (url, callFun) { //get請求方法 axios.get(url).then(callFun) .catch(function(err){ console.log(err) })}
三、proxy代理
在config-index.js
文件下找到proxyTable
設置代理
例如我的vue項目鏈接是 localhost:8080 后臺數據地址是 localhost:8081/api/seller(端口不一樣)
proxyTable: { '/api': { target: 'http://localhost:8081', changeOrigin: true, pathRewrite: { '^/api': '/api' // pathRewrite方法重寫url, 這樣配置出來的url為http://localhost:8081/api/seller // '^/api': '/' // pathRewrite方法重寫url, 這樣配置出來的url為http://localhost:8081/seller } } }
四、數據調用
在想調用數據的vue頁面中寫入如下代碼
js部分
<script>import {getHttp} from '../static/js/httpserver.js'export default { data () { return { seller: {} } }, methods: { shangjia: function () { let url = '/api/seller' getHttp(url, function (res) { res = res.data console.log(res) }) } }}</script>
html部分
<template><div id="app"> <div @click='shangjia()'><router-link to='/seller'>商家</router-link></div><router-view></router-view></div></template>
推薦可以模擬數據的網址
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答