0.$data,$el,$watch 都是vm(實例)所擁有的方法或者屬性 能夠經過$+vue實例中屬性--->直接操做表達
1.obejct.freeze() 方法能夠凍結一個對象。一個被凍結的對象不再能被修改;凍結了一個對象則不能向這個對象添加新的屬性,不能刪除已有屬性,
2. <!-- 綁定一個disabled只要值不爲空 就是true --> <li :disabled = "lop">{{res}}</li>
3. <button v-on:[event] ='evenFun'></button>綁定一個事件名稱event(動態參數),該綁定事件類型的方法不能用@來綁定
動態綁定元素屬性值 <li v-bind:[names] = 'url'></li>
對動態參數的值的約束:
動態參數預期會求出一個字符串,異常狀況下值爲 null。這個特殊的 null 值能夠被顯性地用於移除綁定。任何其它非字符串類型的值都將會觸發一個警告。
並且動態參數值只能小寫,不支持大寫
<!-- 在 DOM 中使用模板時這段代碼會被轉換爲 `v-bind:[someattr]` -->
<a v-bind:[someAttr]="value"> ... </a>
4.
computed: 計算屬性有緩存:計算屬性是基於它們的響應式依賴進行緩存的;只在相關響應式依賴發生改變時它們纔會從新求值。這就意味着只要 message 尚未發生改變,屢次訪問 reversedMessage 計算屬性會當即返回以前的計算結果,而沒必要再次執行函數。
咱們爲何須要緩存?假設咱們有一個性能開銷比較大的計算屬性 A,它須要遍歷一個巨大的數組並作大量的計算。而後咱們可能有其餘的計算屬性依賴於 A 。若是沒有緩存,咱們將不可避免的屢次執行 A 的 getter!若是你不但願有緩存,請用方法來替代。
<p>{{wwws}}</p> //表明返回的computed計算值
computed : {
wwws () {
return Date.now();
}
}
<div>{{gets}}</div>
默認是每一個計算屬性計算時有get函數,能夠進行緩存
gets: {
get () { // ,在數據未發生變化時,優先讀取緩存
return this.text + this.str
},
set() { //在設置數據時觸發
return this.text + this.str
}
}
5. watch:觀察和響應 Vue 實例上的數據變更:偵聽屬性
6. <li v-bind:class="bd">bds</li>//綁定一個返回對象的計算屬性含的class,這是一個經常使用且強大的模式:
bd () {
return {
active:'active',
en:'en'
}
}
result——><li class="active en">bds</li>
<li v-bind:class="[on ? on1 : on2]">on</li> //據條件切換列表中的 class,能夠用三元表達式
<div v-bind:class="[{ active: isActive }, errorClass]"></div>//當有多個條件 class 時這樣寫有些繁瑣。因此在數組語法中也可使用對象語法
7.Vue 不能檢測如下數組的變更:
當你利用索引直接設置一個數組項時,例如:vm.items[indexOfItem] = newValue
當你修改數組的長度時,例如:vm.items.length = newLength
舉個例子:
var vm = new Vue({
data: {
items: ['a', 'b', 'c']
}
})
vm.items[1] = 'x' // 不是響應性的
vm.items.length = 2 // 不是響應性的
Vue 不能檢測對象屬性的添加或刪除::::
對於已經建立的實例,Vue 不容許動態添加根級別的響應式屬性。可是,能夠
使用 Vue.set(object, propertyName, value)或者vm.$set()方法向嵌套對象添加響應式屬性;
JS:Object.assign()方法用於將全部可枚舉屬性的值從一個或多個源對象複製到目標對象。它將返回目標對象。
Object.assign(target, ...sources);target: 目標對象 sources: 源對象
var obj1 = {
b:2,
a:1
}
var obj2 = {
c:3,
d:4
} Object.assign(obj1,obj2);//obj2和obj1合併
爲已有對象賦值多個新屬性:::::
vm.userProfile = Object.assign({}, vm.userProfile, {
age: 27,
favoriteColor: 'Vue Green'
});
8.想要顯示一個數組通過過濾或排序後的版本,而不實際改變或重置原始數據--用computed和filter返回過濾值便可
<li v-for="fa of fas">{{fa}}</li>
data () (
return { num:[1,2,3,4] }
},
computed:{
fa () {
return this.num.filter(function (num) {
return num > 3
})
}
}
在計算屬性不適用的狀況下 (例如,在嵌套 v-for 循環中) 你可使用一個方法: 傳參給循環對象,methods展現返回
<li v-for="n in even(mum)">{{ n }}</li> v-for能夠接受一個有參函數
methods : {
even (num) {
retun this.num.filter(function (num) {
return num > 3
})
}
}
9.v-if 與 v-for 同時使用
當v-if與v-for處於同一級時 v-for的優先級比v-if高
這意味着 v-if 將分別重複運行於每一個 v-for 循環中
當你只想爲部分項渲染節點時,這種優先級的機制會十分有用,以下:
<li v-for="todo in todos" v-if="!todo.isComplete">
{{ todo }}
</li>
上面的代碼將只渲染未完成的 todo。
***10: props
傳遞靜態或動態 Prop:
--------靜態傳一個props:
<el-html tis="你哈"></el-html>//你哈
Vue.component('el-html',{
props:{
tis:{
type:String
}
}
template:'<h2>{{tis}}</h2>'
});
------動態傳一個props:
<el-html :tis="txt"></el-html>//ppp
Vue.component('el-html',{
props:{
tis:{
type:String
}
}
template:'<h2>{{tis}}</h2>'
});
data(){
return {
txt:'ppp'
}
}
------傳入一個對象和數組
<list-si
:name="{ name1:'qqq', name2:'eee' }"
age="[1,2,3]"
></list-si>
Vue.component('list-si',{
props:{
name:{
type:Object
}
}
props:['age']
template:'<h4>{{name.name1}} {{age[0}}</h4>' //qqq 1
});
================================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<div class="list">
<ol>
<to-list :item = "list" v-for="list in lists"></to-list>
<!-- to-list是父組件,將經過bind綁定一個值item,子組件li經過props接受 -->
</ol>
<div v-html="res" :title="oop + 'ppo'"></div>
<p>{{lop + lop}}</p>
<!-- <p>{{ ok ? 'YES' : 'NO' }}</p> -->
<p>{{lop+str.split('')}}</p>
<!-- <p v-if="fs">fff</p> -->
<h3 v-on:click="fs = !fs">ffrf</h3>
<p v-if="fs">{{shows}}</p>
<!-- 綁定一個disabled只要值不爲空 就是true -->
<li :disabled = "lop">{{res}}</li>
<button v-on:[event].prevent = 'evenFun'>回值</button>
<div :[namesAtr]="url">fff</div>
computed:
<p>{{wwws()}}</p> //調用方法返回值
<p>{{wwws}}</p> //表明返回的computed計算值
計算屬性有緩存:計算屬性是基於它們的響應式依賴進行緩存的;只在相關響應式依賴發生改變時它們纔會從新求值。這就意味着只要 message 尚未發生改變,屢次訪問 reversedMessage 計算屬性會當即返回以前的計算結果,而沒必要再次執行函數。
<div>{{datas}}</div>
<div>{{datas2()}}</div>
<div>{{js}}</div>
<div>{{gets}}</div>
watch:觀察和響應 Vue 實例上的數據變更:偵聽屬性
<!-- <div>{{ fullName }}</div> -->
class style綁定:
<li class="active1" v-bind:class="{active:actives,active2:actives2}">actives</li>
<li v-bind:class="cd">cds</li>//對象class
<li v-bind:class="bd">bds</li>//綁定一個返回對象的計算屬性含的class
<!-- 數組綁定class -->
<li v-bind:class="[on,on1,on2]">on1</li>
<li v-bind:class="[on ? on1 : on2]">on</li> //據條件切換列表中的 class,能夠用三元表達式
<div v-bind:class="[{ active: isActive }, errorClass]"></div>//當有多個條件 class 時這樣寫有些繁瑣。因此在數組語法中也可使用對象語法:
<!-- 綁定style -->
<li :style="{fontSize:aco + 'px'}">嗯嗯嗯</li>
<li :style="styles">this is fangsi</li>
<!-- v-for索引 鍵 -->
<li v-for="(ins,key,index) of inss">{{ins}} {{key}} {{index}}</li>
Vue 不能檢測如下數組的變更:
當你利用索引直接設置一個數組項時,例如:vm.items[indexOfItem] = newValue
當你修改數組的長度時,例如:vm.items.length = newLength
舉個例子:
var vm = new Vue({
data: {
items: ['a', 'b', 'c']
}
})
vm.items[1] = 'x' // 不是響應性的
vm.items.length = 2 // 不是響應性的
Vue 不能檢測對象屬性的添加或刪除::::
對於已經建立的實例,Vue 不容許動態添加根級別的響應式屬性。可是,能夠
使用 Vue.set(object, propertyName, value)或者vm.$set()方法向嵌套對象添加響應式屬性;
JS:Object.assign()方法用於將全部可枚舉屬性的值從一個或多個源對象複製到目標對象。它將返回目標對象。
Object.assign(target, ...sources);target: 目標對象 sources: 源對象
var obj1 = {
b:2,
a:1
}
var obj2 = {
c:3,
d:4
} Object.assign(obj1,obj2);//obj2和obj1合併
爲已有對象賦值多個新屬性:::::
vm.userProfile = Object.assign({}, vm.userProfile, {
age: 27,
favoriteColor: 'Vue Green'
})
</div>
<script>
Vue.component('to-list',{
props:['item'],
template:'<li>{{ item.text }}</li>'
});
var vm = new Vue({
el:'.list',
data () {
return {
lists:Object.freeze([ //Object.freez阻止死對象被修改,也意味着響應系統沒法再追蹤變化。
{text:'1'},
{text:'2'}
]),
text:'js',
res:'<li>JavaScript</li>',
oop:'oop',
lop:'lop',
str:'java',
fs:true,
shows:'ppp',
url:'a.html',
event:"mouseleave",
namesatr:'href',
actives:true,
actives2:true,
//對象class
cd : {
on : true,
ons : true
},
// 數組class
on: 'true', on1: 'true2', on2: 'true3',
aco:2,
styles:{
fontSize:'20px',
color:'red',
disPlay:'block'
},
inss:{
insss:'oo',
www:'ww',
eee:'ee'
}
}
},
computed : {
wwws () { return this.oop.split('').reverse().join(''); },
datas () { return Date.now(); },
js () { return Date.now() },
gets: {
get () { // 默認是每一個計算屬性計算時有get函數,能夠進行緩存,在數據未發生變化時,優先讀取緩存
return this.text + this.str
},
set() { //在設置時值觸發
return this.text + this.str
}
},
// 綁定一個返回對象的計算屬性含的class
bd () {
return {
active:'active',
en:'en'
}
}
},
watch: {
},
created () {
console.log(this.text);
},
methods:{
evenFun () {
alert(0);
},
wwws () {
return this.oop.split('').reverse().join('');
},
datas2 () {
return Date.now()
}
}
});
console.log(vm.$el); //輸出div
// $data,$el,$watch 都是vm(實例)所擁有的方法或者屬性
vm.$data.oop = 'ui';
vm.$data.str = 'kkk';
vm.$set(vm.inss,'hu','pp');//使用 Vue.set(object, propertyName, value)或者vm.$set()方法向嵌套對象添加響應式屬性; vm.$set是Vue.set的別名,二者功能同樣
vm.inss = Object.assign({},vm.inss,{
k:'ee',
l:'hh'
});
</script>
</body>
</html>
複製代碼
(1) //首當其衝
Vue.use(Router);
export defalut new Router({
routes:[
{
path:'/',
name:'first',//此模板中使用router-view標籤將要用的子頁面(first-child)拿來,子路由的狀況通常用在一個頁面有他的基礎模版,而後它下面的頁面都隸屬於這個模版,
component:first,
//主頁中的子路由顯示項
children:[
{
path:'/first-child',
name:''
}
]
}
]
})
(2)路由傳參
@經過router-link:to綁定所需參數向lonarui4傳參:
<router-link :to="{name:'lonarui4',path:'/lonarui4',params:{name1:'哈哈'}}">go to lonarui4</router-link> 在lonarui4模板中用{{$route.params.name1}}接受便可
@經過點擊事件用全局$router給地址路徑追加($router.push)值傳參:
<div @click="to_lonarui4"></div>
export defalut {
methods:{ 點擊跳轉傳參
to_lonarui4 () {
this.$router.push({
name:'lonarui4', 用name來*識別*,保持與query一致性 或者用 path:'/lonarui4'
params:{ //注意params有個坑————瀏覽器刷新會致使傳的參數不存,將params換成query便可;這是因爲query與params傳參機制不同,形成的差別,若是要隱藏參數用params,若是強制刷新不被清除用query。
page:'1',
code:'00'
}
})
}
}
}
lonarui4頁面接受:
mounted(){
console.log(this.$route.parmas.page);
console.log(this.$route.query.page);
}
@經過配置路由index.js來傳參
export defalut new Router({
route:[
{
path:'/lonarui4/:id/:conts', 在url中用:「:字段」 配置參數
//path:'/lonarui4/:id(\\d+)/:conts',//加入了正則,再傳遞數字以外的其餘參數,組件就沒有辦法接收到。
name:'lonarui4',
component:lonarui4
}
]
});
在主模板中 <router-link to="lonarui/目標id/內容"></router-link>
在lonarui4模板中 用{{$route.params.id}} {{$route.params.conts}} 接收
(3)路由中的鉤子函數
beforeRouteEnter:在路由進入前的鉤子函數。
beforeRouteLeave:在路由離開前的鉤子函數。
三個參數:
to:路由將要跳轉的路徑信息,信息是包含在對像裏邊的。
from:路徑跳轉前的路徑信息,也是一個對象的形式。
next:路由的控制參數,經常使用的有next(true)和next(false)。
{
path:'/lonarui4/:lisId/:listTit',
name:'lonarui4',
component:lonarui4,
beforeEnter:(to,from,next)=>{ 若是使用鉤子函數,對應要跳轉的lonarui4所在的router-link會失效
console.log('我進入了lonarui4模板');
console.log(to);
console.log(from);
console.log(next);
}
},
--------------------過渡---------------
.fade-enter {
opacity:0;
}
.fade-leave{
opacity:1;
}
.fade-enter-active{
transition:opacity .5s;
}
.fade-leave-active{
opacity:0;
transition:opacity .5s;
}
<transition name="fade" class="fade-enter-active">
<router-view></router-view> //加載子路由可設置過渡
</transition>
** css過渡類名: ** 組件過渡過程當中,會有四個CSS類名進行切換,這四個類名與transition的name屬性有關,好比name=」fade」,會有以下四個CSS類名:
fade-enter:進入過渡的開始狀態,元素被插入時生效,只應用一幀後馬上刪除。
fade-enter-active:進入過渡的結束狀態,元素被插入時就生效,在過渡過程完成後移除。
fade-leave:離開過渡的開始狀態,元素被刪除時觸發,只應用一幀後馬上刪除。
fade-leave-active:離開過渡的結束狀態,元素被刪除時生效,離開過渡完成後被刪除。
-------------------配置404--------------------
{
path:'*', //這裏的path:’*’就是找不到頁面時的配置
component:'Error' //404頁面
}
<router-link to="/b">瞎寫的</router-link> 跳轉找不到這個路徑所示頁面,啓動Error頁面
複製代碼
11.------------------------------vueX------------------------------------------------
Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。它採用集中式存儲管理應用的全部組件的狀態,
這個狀態自管理應用包含如下幾個部分:
state,驅動應用的數據源;
view,以聲明方式將 state 映射到視圖;
actions,響應在 view 上的用戶輸入致使的狀態變化。
每個 Vuex 應用的核心就是 store(倉庫)。「store」基本上就是一個容器,它包含着你的應用中大部分的狀態 (state)
Vuex 的狀態存儲是響應式的。當 Vue 組件從 store 中讀取狀態的時候,若 store 中的狀態發生變化,那麼相應的組件也會相應地獲得高效更新。
你不能直接改變 store 中的狀態。改變 store 中的狀態的惟一途徑就是顯式地提交 (commit) mutation。這樣使得咱們能夠方便地跟蹤每個狀態的變化,從而讓咱們可以實現一些工具幫助咱們更好地瞭解咱們的應用
例:
創建store.js,安裝vuex
store.js::::
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state = { //state存貯要公用的數據
num:1,
str:'qq'
}
const mutations = { //mutations對存儲的數據進行按需操做
add (state) {
state.num++
},
changStr (state) {
console.log(state.str)
}
export defalut new VueX.Store{ 導出全局的$store對象,以便各個模板使用
state
}
}
//模板中調用使用
<div>{{$store.state.num}}</div> 1
<span @click="$store.commit('add')">add+</span> //用comit提交觸發mutatons中函數
<span @click="$store.commit('changStr')">{{$store.state.str}}</span> qq
import store form '....'
1. 用computed獲取store中的狀態(state)值
(1)第一種方法:直接經過計算返回
computed:{
getState () {
return this.$store.state.num //模板調用 <div>{{getSate}}</div>
}
}
(2)第二種方法:經過mapState的對象來賦值
先引入mapState import {mapState} from 'vuex'
computed:mapState(
getState:state => state.num //模板調用 <div>{{getSate}}</div>
)
(3)第二種方法:經過mapState的對象設置數組來獲取state
computed:mapState(["num"]), //模板調用 <div>{{getSate}}</div>
---store.js:::
const state = { //state存貯要公用的數據
num:1,
str:'qq'
}
*****可是吶:若是咱們須要在一個computed中處理不少個數據時,那這時就不能這樣寫了,由於一個模板中只能有一個computed起做用,那咋辦嘛,用es6的擴展運算符便可:looK!
****computed:{
...mapState({
getState:state => state.num
}),
...mapState(["num"]) //這樣寫簡單明瞭
}
2.Mutations修改state狀態
(1)$store.commit() 經過commit提交獲得state值
<span @click="$store.commit('add',n)">add+</span> //用comit提交觸發mutatons中函數 可傳值n到mutations中
const mutations = {
add(state,n) {
state.num+=n
}
}
(2)使用mapMutations修改state狀態
先引入mapMutations import { mapState,mapMutations } from 'vuex';
methods:mapMutations(
['add','reduce']
)
調用 <div> @click="add">{{$store.state.num}}</div>
******同computed同樣,methods也只能在模板中出現一次,因此用擴展符:
**methods:{
...mapMutations('add','reduce')
}
3.getters計算過濾操做
有這樣一個需求哈:從store中取值時,首先給所需值過濾操做,怎麼實現?,因此vux提供了getters這個方法用於數據的過濾操做
如今咱們對num預先操做下,讓他每次更改值時,加10
const state = {
num:1
}
const getters = {
num (state) {
return state.num += 10
}
}
//export導出getters
export default new Vuex.Store({
state,mutations,getters
});
模板中調用:::
import {mapState,mapMutations,mapGetters} from 'vuex'
<p>{{num}}</p> //11
computed: {
...mapState(['num']),
num () {
return this.$store.$getters.num
}
//因爲vux提供了mapGetters 因此像...mapState(['num'])能夠用擴展符來寫
mapGetters(['num'])
}
4.actions異步修改狀態
actions和mutations的基本功能都同樣,都是顯示提交(commit)更改state狀態,
惟一不一樣:actions是異步來調用修改mutations中定義的數據(數據在函數中)狀態,而mutations是同步來修改state中的數據狀態
//上碼子:
const = state {
num:0
}
//用mutations同步更改state狀態
const mutaions = {
add(state,n) {//傳參
state.num += n
}
}
用actions異步提交(commit)更改mutaions中的數據;
context:上下文對象,這裏你能夠理解稱store自己。
{commit}:直接把commit對象傳遞過來,可讓方法體邏輯和代碼更清晰明瞭。
const actions = {
adds (contTxt) {
contTxt.commit('add',10) //調用store的commit方法提交進行更改狀態
}
//更明瞭的寫法
adds ({commit}) {將store的commit方法直接以對象的形式做爲形參,提供函數體調用修改mutiaons中的數據
commit('adds',10)
}
}
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export defalut new Vuex.Store({
state,
mutaions,
getters,
actions
});
//在模板中調用
<div @click="adds">{{num}}</div> //點擊後 10
export defalut {
computed : {
...mapstate([num])
},
methods : {
...mapActions(['adds'])
}
}
5.module(狀態管理器的模塊組)
隨着項目的複雜性增長, 共享的狀態愈來愈多,這時候咱們就須要把咱們狀態的各類操做進行一個分組,分組後再進行按組編寫。
const firstModlue = {
state: {
number:1
},
mutations: {
adds (state) {
state.number++
}
},
getters: {
number (state) {
return state.number += 10
}
},
actions: {
addsActions ({commit}) {
commit('adds')
}
}
}
export defalut new Vuex.Store({
modules: {
first:firstModlue
}
});
//模板中調用
<div>{{$store.state.first.number}}</div> //調用modules中的first狀態組
<div>{{number}}</div>
computed: {
...mapState({
number: state => this.$store.state.first.number
})
}
複製代碼
1.在main.js導入:
css
import axios from 'axios'
//將axios賦值到原型上:
Vue.prototype.$ajax = axios
複製代碼
2.模板中碼子展現:html
<style>
img {width: 30px;}
</style>
<template>
<div>
<ul>
<li v-for="(list,index) of lists" :key="list.id">
<span>{{list.id}}</span>
<i>{{list.name}}</i>
<em>{{list.des}}</em>
</li>
<hr>
<ul>
<li v-for="good of goods">
<span>{{good.t1}}</span>
<span><img :src="good.t2"></span>
<span>{{good.t3}}</span>
</li>
</ul>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
lists:[],
goods:[],
URL:{
url1:"http://www.wujiaweb.com/api",
},
getAxios() {
調用全局$ajax
this.$ajax
.get(this.URL.url1, { id: 1, name: "r" })
.then(res => {
let resResult = res.data.data;
console.log(resResult);
let _this = this;
resResult.favourite_goods.forEach((val) => {
_this.lists.push({
id: val.goods_id,
name: val.goods_name,
des: val.goods_remark
});
});
resResult.hot_goods.forEach((val) => {
console.log(val);
_this.goods.push(
{
t1:val.goods_sn,
t2:_this.URL.url1.substr(0,23) + val.original_img,
t3:val.goods_name
}
)
})
},(error) => {
console.log(error);
}).catch(res => {
console.log(res);
});
}
};
},
mounted() {
let _this = this;
this.$nextTick(() => {
getUser();
async function getUser() {
try {
const response = await _this.getAxios();
console.log(response);
} catch (error) {
console.error(error);
}
}
});
}
};
</script>
複製代碼
若是一次性要請求多個接口呢(執行多個併發請求):
處理併發請求的助手函數:vue
axios.all(iterable)
axios.spread(callback)
複製代碼
以下使用:java
mounted () {
let _this = this;
function get1() {
return _this.$ajax.get("http://www.wujiaweb.com/api/goods/advertise");
}
function get2() {
return _this.$ajax.get("http://www.wujiaweb.com/api/goods/category");
}
function get3() {
return _this.$ajax.get("http://www.wujiaweb.com/api/cart");
}
_this.$ajax.all(
[get1,get2,get3]
).then(
_this.$ajax.spred(data1,data2,data3) { //經過sperd獲得all中請求的接口, data1等表明$ajax.all中的get
let a = data1.data.data.filter(val => {
return val.ad_id > 70;
});
console.log(a);
}
)
}
複製代碼
請求方法的別名
爲方便使用,官方爲全部支持的請求方法提供了別名,能夠直接使用別名來發起請求:node
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
在使用別名方法時, url、method、data 這些屬性都沒必要在配置中指定。
複製代碼
通常在咱們實際項目中,都會封裝一個全局的axios用於遠程數據拉去,
爲何要封裝?
封裝有助於全局使用,設置統一的請求攔截,有助於維護
來吧,碼子展現ios
1.首先創建http.js文件
2.引入axios和qs,
3.設置攔截器,
4.按需設置要用的請求方法
es6
import axios from 'axios'
import qs from 'qs'//序列化字符串,處理髮送請求的參數 axios發送的數據不是json格式,若須要json格式,添加此庫
axios.interceptors.response.use(response => { // 對響應數據作點什麼
return response.data
}, function (error) {
console.log(error);
});
axios.interceptors.request.use(config => { // 對響應錯誤作點什麼
return config;
}, function (error) {
return Promise.reject(error)
});
export default {
// 全局token
get(url, params) {
return axios({
method: 'get',
url: url,
params,
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
}
})
},
post(url, data) {
return axios({
method: 'post',
url: url,
data: qs.stringify(data),
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
}
})
},
form(url, formdata) {
return axios({
method: 'post',
url: url,
data: formdata,
withCredentials: true,
})
},
getJson(url) {
return axios({
method: 'get',
url: url
})
}
}
複製代碼
5.在main.js 入口文件中引入http.jsweb
import http from './assets/js/http'
複製代碼
6.模板中調用使用面試
mounted () {
this.$http.post(
'http://www.xuefu.com/data/student',
{
name:'_'
}
).then(res => {
console.log(res);
}).catch(res => {})
}
複製代碼