Vue 學(xué)習(xí)筆記1(01-39)
學(xué)習(xí)地址:https://ke.qq.com/course/279700
目錄:
- 01-01 git下載代碼
- 02-27 Vue2.x
- 28-39 路由精講
- 40-49 Vue-Cli3.0
- 50-64 Vue2.x-實戰(zhàn)項目(個人博客)
- 65-76 Vue2.x-實戰(zhàn)項目(用戶管理)
- 77-87 Vuex
download
01 第1課到25課代碼下載
git clone https://github.com/hemiahwu/vue-basic.git
cd vue-basic
git checkout lesson-* # *為 1~25
vue2
02 Vue2.x-初識Vue及引入CDN
vue的引入
<!-- 開發(fā)環(huán)境版本,包含了有幫助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
或者
<!-- 生產(chǎn)環(huán)境版本,優(yōu)化了尺寸和速度 -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
03 Vue2.x-實例化Vue對象
app.js
// 實例化Vue對象
new Vue({
el: '#vue-app',
data: {
name: 'Allenem',
job: 'student'
}
});
/*
* el:element 只能掛載到根容器上
* data:用于數(shù)據(jù)存儲
*/
html中引入數(shù)據(jù)
<script src="app.js"></script>
{{ name }}
{{ job }}
04 Vue2.x-數(shù)據(jù)和方法
(1)無參函數(shù)
app.js
// methods 用于存儲各種方法
methods: {
greet: function(){
return 'Good Morning!'
}
}
index.html中使用方法
<!-- 正確 -->
{{greet()}}
<!-- 顯示如下 -->
<!-- Good Morning! -->
<!-- 錯誤 -->
{{greet}}
<!-- 顯示如下 -->
<!-- function () { [native code] } -->
(2)有參函數(shù)
app.js
methods: {
greet: function(time){
return 'Good '+time+' !';
}
}
index.html中使用方法
<!-- 正確 -->
{{ greet('Night') }}
<!-- 顯示如下 -->
<!-- Good Night ! -->
<!-- 錯誤 -->
{{ greet(Night) }}
<!-- 顯示如下 -->
<!-- Good undefined ! -->
(3)方法中用data中的屬性
直接使用this.*
,不用this.data.*
app.js
methods: {
greet: function(time){
return 'Good '+ time + this.name+' !';
}
}
05 Vue2.x-屬性綁定
綁定屬性
app.js
data中添加
website: 'https://github.com/'
index.html
<a v-bind:href="website">websit</a>
或者簡寫
<a :href="website">websit</a>
綁定標(biāo)簽
app.js
data中添加
websiteTag: "<a
index.html
<!-- 正確 -->
<p v-html="websiteTag">websit</a>
<!-- 錯誤 -->
{{ websiteTag }}
<!-- 顯示如下 -->
<!-- <a >websit</a> -->
06 Vue2.x-事件(點擊:雙擊:鼠標(biāo)事件)
不傳參單擊雙擊
注意:綁定事件里方法不傳參可以不加括號仍然識別為方法,但在{{}}里一定要寫括號才會識別為方法
app.js
data: {
age: 20,
},
methods: {
add: function(){
this.age++;
},
dec: function(){
this.age--;
},
}
index.html
<!-- 單擊 -->
<button v-on:click='add'>加一歲</button>
<button @click='dec'>減一歲</button>
<!-- 雙擊 -->
<button v-on:dblclick='add'>加一歲</button>
<button @dblclick='dec'>減一歲</button>
<p>My age is {{ age }}</p>
傳參單擊雙擊
app.js
methods: {
add: function(val){
this.age += val;
},
dec: function(val){
this.age -= val;
},
}
index.html
<button v-on:click='add(1)'>加一歲</button>
<button @click='dec(1)'>減一歲</button>
<button v-on:dblclick='add(10)'>加十歲</button>
<button @dblclick='dec(10)'>減十歲</button>
鼠標(biāo)滾動獲取當(dāng)前位置事件
app.js
methods: {
updateXY: function(event){
this.x = event.offsetX;
this.y = event.offsetY;
},
}
index.html
<div id="canvas" @mousemove='updateXY'>
{{x}},{{y}}
</div>
07 Vue2.x-事件修飾符(once:prev:stop)
app.js
// 無變化
index.html
<div id="canvas" @mousemove='updateXY'>
{{x}},{{y}} --
<span @mousemove.stop=''>stop moving</span>
</div>
<=>
methods:{
stopMove: function(event){
event.stopPropagation();
},
}
index.html
<div id="canvas" @mousemove='updateXY'>
{{x}},{{y}} --
<span @mousemove='stopMove'>stop moving</span>
</div>
08 Vue2.x-鍵盤事件及鍵值修飾符(alt:enter)
app.js
data: {
name: 'Allenem',
age: 20,
},
methods: {
logName: function(){
console.log('typing name');
},
logAge: function(){
console.log('typing age');
}
},
index.html
<label>name:</label>
<input type="text" @keyup.enter='logName'>
<label>age:</label>
<input type="text" @keyup.alt.enter='logAge'>
09 Vue2.x-雙向數(shù)據(jù)綁定
app.js
methods: {
logName: function(){
// console.log('typing name');
this.name = this.$refs.name.value;
},
logAge: function(){
// console.log('typing age');
this.age = this.$refs.age.value;
}
},
index.html
<!-- 方法1 -->
<input ref='name' type="text" @keyup='logName'>
<!-- 方法2 -->
<input v-model='age' type="text">
10 Vue2.x-計算屬性Computed
methods 屬性
app.js
methods: {
addA: function(){
console.log('aaa');
return this.a + this.age;
},
addB: function(){
console.log('bbb');
return this.b + this.age;
},
},
index.html
<h1>computed 計算屬性</h1>
<button @click='a++'>Add A</button>
<button @click='b++'>Add B</button>
<p>A: {{a}}</p>
<p>B {{b}}</p>
<p>Age + A {{addA()}}</p>
<p>Age + B {{addB()}}</p>
computed 屬性
app.js
computed: {
addA: function(){
console.log('aaa');
return this.a + this.age;
},
addB: function(){
console.log('bbb');
return this.b + this.age;
},
},
index.html
<h1>computed 計算屬性</h1>
<button @click='a++'>Add A</button>
<button @click='b++'>Add B</button>
<p>A: {{a}}</p>
<p>B {{b}}</p>
<p>Age + A {{addA}}</p>
<p>Age + B {{addB}}</p>
11 Vue2.x-動態(tài)綁定CSS樣式
style.css
span{
background: #f00;
display: inline-block;
padding: 10px;
color: #fff;
margin: 10px 0;
}
.changeColor span{
background: #0f0;
}
.changeLength span:after{
content: "length";
margin-left: 10px;
}
app.js
data: {
changeColor:false,
changeLength:false
},
computed: {
compClasses: function(){
return{
changeColor:this.changeColor,
changeLength:this.changeLength
}
}
},
index.html
<h2>eg2</h2>
<button @click='changeColor = !changeColor'>changeColor</button>
<button @click='changeLength = !changeLength'>changeLength</button>
<div :class='compClasses'>
<span>lucy</span>
</div>
12 Vue2.x-指令v-if
app.js
data: {
err:false,
success:false
},
index.html
<button @click='err=!err'>err</button>
<button @click='success=!success'>success</button>
<p v-if='err'>err</p>
<p v-else-if='success'>200</p>
<p v-show='err'>err</p>
<p v-show='success'>200</p>
13 Vue2.x-指令v-for
app.js
data: {
characters:['allen','janny','mike'],
users:[
{name:'hurry',age:20},
{name:'luccy',age:25},
{name:'zero',age:18},
]
},
index.html
<ul v-for='(item,index) in users' :key='index'>
<li>{{index+1}} - {{item.name}} - {{item.age}}</li>
</ul>
<!-- 會多出3個div -->
<div v-for='(item,index) in users' :key='index'>
<h2>{{item.name}}</h2>
<p>{{index+1}} - {{item.age}}</p>
</div>
<!-- 不會多出3個template -->
<template v-for='(item,index) in users' :key='index'>
<h2>{{item.name}}</h2>
<p>{{index+1}} - {{item.age}}</p>
</template>
14 Vue2.x-實戰(zhàn)DEMO
app.js
data: {
health:100,
ended:false
},
methods: {
punch:function(){
this.health -= 10;
if(this.health <= 0){
this.ended = true;
}
},
restart:function(){
this.health = 100;
this.ended = false;
}
},
index.html
<h1>Bag-Demo</h1>
<!-- 圖片 -->
<div id="bag" :class="{burst: ended}"></div>
<!-- 進(jìn)度 -->
<div id="bag-health">
<div :style="{width: health + '%'}"></div>
</div>
<!-- 控制按鈕 -->
<div id="control">
<button @click='punch' v-show='!ended'>使勁敲</button>
<button v-on:click='restart'>重新開始</button>
</div>
style.css
h1{
width: 200px;
margin: 0 auto;
text-align: center;
}
#bag{
width: 200px;
height: 500px;
margin: 0 auto;
background: url(img/bag.png) center no-repeat;
background-size: 80%;
}
#bag.burst{
background-image: url(img/bag-burst.png)
}
#bag-health{
width: 200px;
border: 2px #000 solid;
margin: 0 auto 20px auto;
}
#bag-health div{
height: 20px;
background: crimson;
}
#control{
width: 200px;
margin: 0 auto;
}
#control button{
margin-left: 20px;
}
15 Vue2.x-實例化多個Vue對象
app.js
// 實例化Vue對象
var one = new Vue({
el: '#vue-app-one',
data: {
title: 'one 的內(nèi)容'
},
methods: {
},
computed: {
greet:function(){
return 'hello app one';
}
},
});
var two = new Vue({
el: '#vue-app-two',
data: {
title: 'two 的內(nèi)容'
},
methods: {
changeTitle:function(){
one.title = 'changed';
}
},
computed: {
greet:function(){
return 'hello app one';
}
},
});
16 Vue2.x-初識組件的應(yīng)用
app.js
Vue.component("greeting",{
template:`
<div>
<p> {{name}}:大家好,給大家介紹一下我的朋友@關(guān)曉彤</p>
<button @click='changeName'>點我</button>
</div>
`,
data:function(){
return {
name:'鹿晗'
}
},
methods:{
changeName:function(){
this.name = this.name == '鹿晗'?'Hery':'鹿晗'
}
}
})
17 Vue2.x-搭建腳手架CLI
部分特點
- 腳手架是通過webpack搭建的開發(fā)環(huán)境
- 使用es6語法
- 打包和壓縮js為一個文件
- 項目在環(huán)境中編譯,而不是瀏覽器
- 實現(xiàn)頁面自動刷新
- ...
vue-cli的使用
- 安裝 nodejs ,一般選擇安裝LTS(長期穩(wěn)定版)版本。官網(wǎng):https://nodejs.org/en/
# 在terminal、cmd、powershell 中 # 輸入 `node -v` 查看 node 版本號 node -v
# 輸入 `npm -v` 查看 npm 版本號 npm -v
- 安裝 cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
- 安裝 Vue CLI 3.x
npm install -g @vue/cli # OR yarn global add @vue/cli
# 輸入 `vue --version` 查看 npm 版本號 vue --version # OR vue -V
- 創(chuàng)建一個 Vue 項目
vue create projectName
# 創(chuàng)建項目相關(guān)幫助 vue create --help
- 運行相關(guān)
# Project setup npm install # Compiles and hot-reloads for development npm run serve # Compiles and minifies for production npm run build # Run your tests npm run test # Lints and fixes files npm run lint
- (PS)舊版本 Vue CLI 2.x
npm install -g @vue/cli-init # `vue init` 的運行效果將會跟 `vue-cli@2.x` 相同 vue init webpack my-project
18 Vue2.x-介紹SRC文件流程及根組件App
client
│ .gitignore
│ babel.config.js
│ package.json
│ README.md
│
├─public
│ favicon.ico
│ index.html
│
└─src
│ App.vue
│ main.js
│ router.js
│
├─assets
│ bg.jpg
│
└─components
Component1.vue
Component2.vue
index.html -> main.js -> App.vue ()
<!-- 模板 -->
<template></template>
<!-- 邏輯 -->
<script></script>
<!-- 樣式 -->
<style></style>
19 Vue2.x-組件嵌套
可以在main.js中注冊全局組件
import Users from './component/Users'
Vue.component('users',Users);
也可以在某些組件中調(diào)用
<template>
<div id="app">
<Users></Users>
</div>
</template>
<script>
import Users from './components/Users'
export default {
components:{
'Users':Users
}
}
</script>
20 Vue2.x-組件CSS作用域
<style scoped>
/* `scoped`該組件作用域內(nèi)有效 */
/* 否則子組件相同選項樣式會覆蓋根組件的 */
</style>
21 Vue2.x-實戰(zhàn)Demo(組件嵌套)
略
22 Vue2.x-屬性傳值Props
父組件:
在調(diào)用子組件的位置,綁定自己的屬性,第一個是子組件中的名稱,第二個是父組件中的名稱。
eg:
<Users :usersSon='users'></Users>
子組件:
子組件屬性 props:['usersSon'],
接收傳值。或者用標(biāo)準(zhǔn)寫法
props:{
users:{
type:Array;
requied:true;
},
position:{
type:Array;
requied:true;
},
},
eg:
<template>
<div class="users">
<ul>
<li v-for="(user,index) in usersSon" :key="index" @click="user.show = !user.show">
<h2>{{user.name}}</h2>
<h3 v-show="user.show">{{user.position}}</h3>
</li>
</ul>
</div>
</template>
<script>
export default {
name:'users',
props:['usersSon'],
}
</script>
23 公益廣告
略
24 Vue2.x-傳值和傳引用
傳值:string number boolean,一處變,全部變
引用:array object,一處變,局部變
25 Vue2.x-事件傳值(子to父)
子組件
<h1 @click="tofather">{{title1}} {{title}}</h1>
<script>
export default {
methods: {
tofather: function(){
this.$emit('changed','son to father') //第1個參數(shù)是事件名,第2個參數(shù)是傳遞的值
}
},
}
</script>
父組件
<Header @changed='update($event)' :title="title"></Header>
<!-- $event不能改 -->
<script>
export default {
methods: {
update:function(title){
this.title = title;
}
},
}
</script>
26 Vue2.x-生命周期(鉤子函數(shù))
8個鉤子函數(shù)與 methods 并列。
Header.vue
<script>
export default {
methods: {
tofather: function(){
this.$emit('changed','son to father')
}
},
beforeCreate:function () {
alert('組件實例化之前');
},
created:function () {
alert('組件實例化之后,頁面還未顯示');
},
beforeMount:function () {
alert('組件掛載之前,頁面仍未顯示,但虛擬Dom已經(jīng)配置');
},
mounted:function () {
alert('組件掛載之后,此方法執(zhí)行后,頁面顯示');
},
beforeUpdate:function () {
alert('組件更新之前,頁面仍未更新,但虛擬Dom已經(jīng)配置');
},
updated:function () {
alert('組件更新之后,此方法執(zhí)行后,頁面改變');
},
beforeDestroy:function () {
alert('組件銷毀前');
},
distroyed:function () {
alert('組件銷毀');
}
}
</script>
27 Vue2.x-路由和Http(快速入門)(知識點最后一課第25課)
(1) 安裝路由模塊及引入
npm install vue-router --save
router.js中
import Vue from 'vue'
import Router from 'vue-router'
import Home from './components/Home.vue'
import HelloWorld from './components/HelloWorld.vue'
Vue.use(Router);
export default new Router({
mode: 'history', // 沒有#符號
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/helloworld',
name: '',
component: HelloWorld
}
]
})
main.js中
import router from './router';
new Vue({
router,
...
});
App.vue
<ul>
<li><a href="/">Home</a></li>
<li><a href="/helloworld">Hello</a></li>
<!-- 或者 -->
<li><router-link to="/">Home</router-link></li>
<li><router-link to="/helloworld">Hello</router-link></li>
</ul>
<router-view></router-view>
(2) HTTP
安裝依賴:
npm i vue-resource --save
使用:
main.js中
import VueResource from 'vue-resource';
Vue.use(VueResource);
Home.vue中
created(){
this.$http.get('http://jsonplaceholder.typicode.com/users')
.then((data)=>{
// console.log(data);
this.users = data.body;
})
},
router
28 Vue2.x-路由精講之新建項目
just create an Vue App
29 Vue2.x-路由精講之制作導(dǎo)航
use bootstraps4 by BootstrapCDN (CSS only)
<link rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"
30 Vue2.x-路由精講之配置路由跳轉(zhuǎn)
router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './components/Home'
import About from './components/about/About'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{path:'/',component:Home},
{path:'/about',component:About},
]
})
Header.vue
<router-link to="/about"></router-link>
App.vue
<router-view></router-view>
31 Vue2.x-路由精講之路由小細(xì)節(jié)(redirect和tag)
Header.vue
<!-- 默認(rèn)a標(biāo)簽 -->
<router-link to="/about"></router-link>
<!-- 修改為div標(biāo)簽 -->
<router-link tag='div' to="/about"></router-link>
<!-- 動態(tài)綁定屬性路由 -->
<router-link tag='div' :to="router"></router-link>
<script>
export default {
data(){
return{
router:'/'
}
}
}
</script>
router.js
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{path:'/',component:Home},
{path:'/about',component:About},
{path:'*',redirect:'/'}, //錯誤輸入重定向
]
})
32 Vue2.x-路由精講之路由name屬性及跳轉(zhuǎn)方法
name
{path:'/',name:'homelink',component:Home},
<!-- 注意這幾個符號 : {} " '' " -->
<li><router-link :to="{name:'homelink'}" class="nav-link">主頁</router-link></li>
跳轉(zhuǎn)
<button @click="goOlder" class='btn btn-success'>goOlder</button>
<button @click="goMenu" class='btn btn-success'>goMenu</button>
<button @click="goAdmin" class='btn btn-success'>goAdmin</button>
<script>
export default {
methods:{
goOlder(){
this.$router.go(-1); // 到前一個頁面
},
goMenu(){
// this.$router.replace('/menu'); // 到指定路由頁面
this.$router.push('/menu'); // 到指定路由頁面
},
goAdmin(){
// this.$router.replace({name:'adminLink'}); // 到指定 name 頁面
this.$router.push({name:'adminLink'}); // 到指定 name 頁面
},
}
}
</script>
33 Vue2.x-路由精講之二級路由和三級路由
router.js
{path:'/about',name:'aboutLink',redirect:'/about/histoey',component:About,
// 二級路由
children:[
{path:'/about/histoey',name:'historyLink',component:History},
{path:'/about/contact',name:'contactLink',redirect:'/phone',component:Contact,children:[
// 三級路由
{path:'/phone',name:'phoneNum',component:Phone},
{path:'/personname',name:'personName',component:Personname},
]},
{path:'/about/orderingguide',name:'orderingGuideLink',component:OrderingGuide},
{path:'/about/delivery',name:'deliveryLink',component:Delivery},
]},
about.vue
<!-- 導(dǎo)航的內(nèi)容 -->
<router-view></router-view>
34 Vue2.x-路由精講之導(dǎo)航守衛(wèi)(全局守衛(wèi))
學(xué)習(xí)地址(https://router.vuejs.org/zh/guide/advanced/navigation-guards.html)
main.js中
// 全局守衛(wèi)
router.beforeEach((to,from,next) => {
if(to.path == '/login' || to.path == '/register'){
next()
}else{
alert("還沒有登錄,請先登錄!");
next('/login');
}
})
35 Vue2.x-導(dǎo)航守衛(wèi)(路由獨享-組件內(nèi)守衛(wèi))
后置鉤子(不常用)
router.afterEach((to,from) => {
alert("after each")
})
路由獨享的守衛(wèi)
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
組件內(nèi)的守衛(wèi)
- beforeRouteEnter
- beforeRouteUpdate (2.2 新增)
- beforeRouteLeave
const Foo = {
template: `...`,
beforeRouteEnter (to, from, next) {
// 在渲染該組件的對應(yīng)路由被 confirm 前調(diào)用
// 不!能!獲取組件實例 `this`
// 因為當(dāng)守衛(wèi)執(zhí)行前,組件實例還沒被創(chuàng)建
},
beforeRouteUpdate (to, from, next) {
// 在當(dāng)前路由改變,但是該組件被復(fù)用時調(diào)用
// 舉例來說,對于一個帶有動態(tài)參數(shù)的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉(zhuǎn)的時候,
// 由于會渲染同樣的 Foo 組件,因此組件實例會被復(fù)用。而這個鉤子就會在這個情況下被調(diào)用。
// 可以訪問組件實例 `this`
},
beforeRouteLeave (to, from, next) {
// 導(dǎo)航離開該組件的對應(yīng)路由時調(diào)用
// 可以訪問組件實例 `this`
}
}
beforeRouteEnter 守衛(wèi) 不能 訪問 this,因為守衛(wèi)在導(dǎo)航確認(rèn)前被調(diào)用,因此即將登場的新組件還沒被創(chuàng)建。
不過,你可以通過傳一個回調(diào)給 next來訪問組件實例。在導(dǎo)航被確認(rèn)的時候執(zhí)行回調(diào),并且把組件實例作為回調(diào)方法的參數(shù)。
beforeRouteEnter (to, from, next) {
next(vm => {
// 通過 `vm` 訪問組件實例
})
}
注意 beforeRouteEnter 是支持給 next 傳遞回調(diào)的唯一守衛(wèi)。對于 beforeRouteUpdate 和 beforeRouteLeave 來說,this 已經(jīng)可用了,所以不支持傳遞回調(diào),因為沒有必要了。
beforeRouteUpdate (to, from, next) {
// just use `this`
this.name = to.params.name
next()
}
這個離開守衛(wèi)通常用來禁止用戶在還未保存修改前突然離開。該導(dǎo)航可以通過 next(false) 來取消。
beforeRouteLeave (to, from , next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
next(false)
}
}
beforeRouteLeave(to,from,next){
if(confirm('確認(rèn)離開嗎?') == true){
next()
}else{
next(false)
}
}
36 Vue2.x-路由精講之復(fù)用router-view
router。js修改
{path:'/',name:'homeLink',component:Home,},
為
// 注意 components 的 s
{path:'/',name:'homeLink',components:{
default:Home,
'history':History,
'orderingGuide':OrderingGuide,
'delivery':Delivery
}},
App.vue添加
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-4">
<router-view name="history"></router-view>
</div>
<div class="col-sm-12 col-md-4">
<router-view name="orderingGuide"></router-view>
</div>
<div class="col-sm-12 col-md-4">
<router-view name="delivery"></router-view>
</div>
</div>
</div>
37 Vuv.2x-路由精講之控制滾動行為
router.js中
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 期望滾動到哪個的位置
}
})
eg:
scrollBehavior (to, from, savedPosition) {
// return {x:0,y:100}; // 滾動到(0,100)
// return {selector:'.btn'}; // 滾動到 第一個.btn
// 瀏覽器返回上一頁面時,回到上次瀏覽的位置
if(savedPosition){
return savedPosition
}else{
return {x:0,y:0}
}
}
38 課程總結(jié)及引導(dǎo)
略
39 Vue2.x-實現(xiàn)跨域請求(fetch/axios/proxytable)
(0)預(yù)設(shè)
通過vue-cli3.x版本構(gòu)建的項目使用proxy和以前的項目不同,而且3.x版本構(gòu)建的時候可以選用typescript了。下面記錄一下如何使用proxy跨域。
首先在根目錄創(chuàng)建vue.config.js文件,這個配置文件在運行項目的時候自動加載。
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://xxxx/device/', //對應(yīng)自己的接口
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
這個文件還可以配置其它信息,比如修改端口號,默認(rèn)是8080等等。
最后在頁面發(fā)送請求的時候:
axios.get('/api/getDataPoint').then(res => {
console.log(res)
})
示例如下:
(1)預(yù)設(shè)
proxyTable:{
' /apis': {
//測試環(huán)境
target:'http://www.thenewstep.cn/', //接口域名
change0rigin:true, //是否跨域
pathRewrite: {
'^/apis':'' //需要rewrite重寫的,
}
}
},
(2)fetch
created(){
// fetch
fetch("/apis/test/testToken. php", {
method:"post",
headers: {
"Content-type" :"application/json",
token : "f4c902c9ae5a2a9d8f84868ad064e706"
},
body: JSON.stringify({username: "henry" , password :"321321"})
})
. then( result =>{
// console. log( result)
return result. json()
})
. then(data => {
console. log ( data)
})
}
(3)axios
main.js
import axios from 'axios'
axios.defaults.headers.common[ 'token '] = "f4c902c9ae5a2a9d8f84868ad064e706"
axios.defaults.headers.post ["Content-type"] = "application/j son"
Vue. prototype.$axios = axios
App.vue
this.$axios.post("/apis/test/testToken.php" , {username :"hello",password :"123456"})
.then(data => {
console. log(data)
})