安裝
npm安裝npm install vue
直接引入<script src="https://cdn.jsdelivr.net/npm/vue"></script>
vue init webpack mydemo
切換到項目目錄cd mydemo
安裝模塊npm install
它根據package.json的配置表進行安裝,安裝完後會在mydemo下多一個文件夾node_modules,這裏的文件對應着package.json裏的配置信息。
輸入命令npm run dev
在瀏覽器輸入地址http://localhost:8080,看到如下頁面,說明大功告成,一個Vue項目已經初始化完成!
使用element-uinpm i element-ui -S
完整引入
在 main.js 中寫入以下內容:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
Vue.use(ElementUI);
new Vue({
el: '#app',
render: h => h(App)
});
安裝Vue Devtools調試工具
-
在github下載devtools源碼
https://github.com/vuejs/vue-devtools
-
在vue-devtools-master工程中執行命令
執行cnpm install
,下載依賴 -
執行
npm run build
,編譯源程序 -
編譯完成後修改數據
修改shells >chrome目錄下的mainifest.json 中的persistant爲true -
設置谷歌瀏覽器的擴展程序
勾選開發者模式,然後將剛剛編譯後的工程中的shells目錄下,chrome的整個文件夾直接拖拽到當前瀏覽器中,並選擇啓用,即可將插件安裝到瀏覽器。
引入全局函數
新建common.js文件
var fun = function () {
console.log('hello')
}
export default fun
在main.js中引入import fun from '@/js/common.js'
Vue.prototype.$pubFuc = fun
關閉elint
在配置文件中,註釋掉規則
const createLintingRule = () => ({
// test: /\.(js|vue)$/,
// loader: 'eslint-loader',
// enforce: 'pre',
// include: [resolve('src'), resolve('test')],
// options: {
// formatter: require('eslint-friendly-formatter'),
// emitWarning: !config.dev.showEslintErrorsInOverlay
// }
})
axios
npm install axios
Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。
vue中使用axios
1.安裝axios
npm:
$ npm install axios -S
cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2.配置axios
在項目中新建api/index.js文件,用以配置axios
api/index.js
import axios from 'axios';
let http = axios.create({
baseURL: 'http://localhost:8080/',
withCredentials: true,//是否開啓跨域,更改header的時候就要可以打開
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
transformRequest: [function (data) {
let newData = '';
for (let k in data) {
if (data.hasOwnProperty(k) === true) {
newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
}
}
return newData;
}]
});
function apiAxios(method, url, params, response) {
http({
method: method,
url: url,
data: method === 'POST' || method === 'PUT' ? params : null,
params: method === 'GET' || method === 'DELETE' ? params : null,
}).then(function (res) {
response(res);
}).catch(function (err) {
response(err);
})
}
// request攔截器
service.interceptors.request.use(config => {
console.log(store.getters.token)
if (store.getters.token) {
console.log(getToken())
config.headers['X-Token'] = getToken() // 讓每個請求攜帶自定義token 請根據實際情況自行修改
var token = getToken()
Object.assign(config.headers, { 'token': token })
}
return config
}, error => {
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
})
// respone攔截器
service.interceptors.response.use(
response => {
/**
* code爲非20000是拋錯 可結合自己業務進行修改
*/
console.log(response.data)
const res = response.data
if (res.code !== 20000) {
Message({
message: res.message,
type: 'error',
duration: 5 * 1000
})
// 50008:非法的token; 50012:其他客戶端登錄了; 50014:Token 過期了;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
MessageBox.confirm('你已被登出,可以取消繼續留在該頁面,或者重新登錄', '確定登出', {
confirmButtonText: '重新登錄',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
store.dispatch('FedLogOut').then(() => {
location.reload() // 爲了重新實例化vue-router對象 避免bug
})
})
}
return null
} else {
return response.data
}
},
error => {
if (error.message === 'Network Error' && error.config.url.endsWith('/license')) {
Message({
message: '無法連接到本地代理程序,請確認代理程序是否運行正常!',
type: 'error',
duration: 5 * 1000
})
} else {
console.log(error + ' ' + error.config.url) // for debug
Message({
message: error.message + ' ' + error.config.url,
type: 'error',
duration: 5 * 1000
})
}
return Promise.reject(error)
}
export default {
get: function (url, params, response) {
return apiAxios('GET', url, params, response)
},
post: function (url, params, response) {
return apiAxios('POST', url, params, response)
},
put: function (url, params, response) {
return apiAxios('PUT', url, params, response)
},
delete: function (url, params, response) {
return apiAxios('DELETE', url, params, response)
}
}
這裏的配置了POST、GET、PUT、DELETE方法。並且自動將JSON格式數據轉爲URL拼接的方式
同時配置了跨域,不需要的話將withCredentials設置爲false即可
並且設置了默認頭部地址爲:http://localhost:8080/,這樣調用的時候只需寫訪問方法即可
3.使用axios
注:PUT請求默認會發送兩次請求,第一次預檢請求不含參數,所以後端不能對PUT請求地址做參數限制
首先在main.js中引入方法
import Api from './api/index.js';
Vue.prototype.$api = Api;
然後在需要的地方調用即可
this.$api.post('user/login.do(地址)', {
"參數名": "參數值"
}, response => {
if (response.status >= 200 && response.status < 300) {
console.log(response.data);\\請求成功,response爲成功信息參數
} else {
console.log(response.message);\\請求失敗,response爲失敗信息
}
});