## 一、 發送AJAX請求
### 1. 簡介
vue本身不支持發送AJAX請求,需要使用vue-resource、axios等插件實現
axios是一個基於Promise的HTTP請求客戶端,用來發送請求,也是vue2.0官方推薦的,同時不再對vue-resource進行更新和維護
參考:GitHub上搜索axios,查看API文檔
### 2. 使用axios發送AJAX請求
#### 2.1 安裝axios並引入
npm install axios -S
也可直接下載axios.min.js文件
#### 2.2 基本用法
axios([options])
axios.get(url[,options]);
傳參方式:
1.通過url傳參
2.通過params選項傳參
axios.post(url,data,[options]);
axios默認發送數據時,數據格式是Request Payload,並非我們常用的Form Data格式,
所以參數必須要以鍵值對形式傳遞,不能以json形式傳參
傳參方式:
1.自己拼接爲鍵值對
2.使用transformRequest,在請求發送前將請求數據進行轉換
3.如果使用模塊化開發,可以使用qs模塊進行轉換
axios本身並不支持發送跨域的請求,沒有提供相應的API,作者也暫沒計劃在axios添加支持發送跨域請求,所以只能使用第三方庫
### 3. 使用vue-resource發送跨域請求
#### 3.1 安裝vue-resource並引入
cnpm install vue-resource -S
#### 3.2 基本用法
使用this.$http發送請求
this.$http.get(url, [options])
this.$http.head(url, [options])
this.$http.delete(url, [options])
this.$http.jsonp(url, [options])
this.$http.post(url, [body], [options])
this.$http.put(url, [body], [options])
this.$http.patch(url, [body], [options])
### 4. 練習
百度搜索列表
課後作業:
1.只顯示4條
2.回車後在新頁面中顯示搜索結果
## 二、Vue生命週期
vue實例從創建到銷燬的過程,稱爲生命週期,共有八個階段
## 三、計算屬性
### 1. 基本用法
計算屬性也是用來存儲數據,但具有以下幾個特點:
a.數據可以進行邏輯處理操作
b.對計算屬性中的數據進行監視
### 2.計算屬性 vs 方法
將計算屬性的get函數定義爲一個方法也可以實現類似的功能
區別:
a.計算屬性是基於它的依賴進行更新的,只有在相關依賴發生改變時才能更新變化
b.計算屬性是緩存的,只要相關依賴沒有改變,多次訪問計算屬性得到的值是之前緩存的計算結果,不會多次執行
### 3. get和set
計算屬性由兩部分組成:get和set,分別用來獲取計算屬性和設置計算屬性
默認只有get,如果需要set,要自己添加
## 四、 vue實例的屬性和方法
### 1. 屬性
vm.$el
vm.$data
vm.$options
vm.$refs
### 2. 方法
vm.$mount()
vm.$destroy()
vm.$nextTick(callback)
vm.$set(object,key,value)
vm.$delete(object,key)
vm.$watch(data,callback[,options])
## 五、自定義指令
分類:全局指令、局部指令
### 1. 自定義全局指令
使用全局方法Vue.directive(指令ID,定義對象)
### 2. 自定義局部指令
### 3. 練習
拖動頁面中的元素
onmouseover onmouseout
onmousedown onmousemove onmouseup
## 六、過渡(動畫)
### 1. 簡介
Vue 在插入、更新或者移除 DOM 時,提供多種不同方式的應用過渡效果
本質上還是使用CSS3動畫:transition、animation
### 2. 基本用法
使用transition組件,將要執行動畫的元素包含在該組件內
<transition>
運動的元素
</transition>
過濾的CSS類名:6個
### 3. 鉤子函數
8個
### 4. 結合第三方動畫庫animate..css一起使用
<transition enter-active-class="animated fadeInLeft" leave-active-class="animated fadeOutRight">
<p v-show="flag">網博</p>
</transition>
### 5. 多元素動畫
<transition-group>
### 6. 練習
多元素動畫
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>發送ajax請求</title>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script src="js/vue-resource.min.js"></script>
<script>
window.οnlοad=function(){
new Vue({
el:'#itan',
data:{
user:{
name:'alice',
age:19
},
uid:''
},
methods:{
send(){
axios({
methods:'get',
url:'user.json'
}).then(function(resp){
console.log(resp.data);
}).catch(resp=>{
console.log(resp);
console.log('請求失敗:'+resp.status+','+resp.statusText);
});
},
sendGet(){
/* axios.get('server.php?name=tom&age=23') */
axios.get('server.php',{
params:{
name:'alice',
age:19
}
})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log('請求失敗:'+err.status+','+err.statusText);
});
},
// 使用transformRequest,在請求發送前將請求數據進行轉換
sendPost(){
// axios.post('server.php',{
// name:'alice',
// age:19
// })
// axios.post('server.php','name=alice&age=20&') //方式1
axios.post('server.php',this.user,{
transformRequest:[
function(data){
let params='';
for(let index in data){
params+=index+'='+data[index]+'&';
}
return params;
}
]
})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log('請求失敗:'+err.status+','+err.statusText);
});
},
getUserById(uid){
axios.get(`https://api.github.com/users/${uid}`)
.then(resp => {
// console.log(resp.data);
this.user=resp.data;
});
},
//跨越請求
sendJSONP(){
//https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&fields=word&word=a
this.$http.jsonp('https://sug.so.360.cn/suggest',{
params:{
word:'a'
}
}).then(resp => {
console.log(resp.data.s);
});
},
sendJSONP2(){
//https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json=1&p=3&sid=1420_21118_17001_21931_23632_22072&req=2&csor=1&cb=jQuery110208075694879886905_1498805938134&_=1498805938138
this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
params:{
wd:'a'
},
jsonp:'cb' //百度使用的jsonp參數名爲cb,所以需要修改
}).then(resp => {
console.log(resp.data.s);
});
}
}
})
}
</script>
</head>
<body>
<div id="itan">
<button @click="send">發送AJAX請求</button>
<button @click="sendGet">GET方式發送AJAX請求</button>
<button @click="sendPost">POST方式發送AJAX請求</button>
GitHub ID: <input type="text" v-model="uid">
<button @click="getUserById(uid)">獲取指定GitHub賬戶信息並顯示</button>
<br>
姓名:{{user.name}} <br>
頭像:<img :src="user.avatar_url" alt="">
<hr>
<button @click="sendJSONP">向360搜索發送JSONP請求</button>
<button @click="sendJSONP2">向百度搜索發送JSONP請求</button>
<hr>
<br>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>發送AJAX請求</title>
<style>
.current{
background-color:#ccc;
}
</style>
<script src="js/vue.js"></script>
<script src="js/vue-resource.min.js"></script>
<script>
window.οnlοad=function(){
new Vue({
el:'#itany',
data:{
keyword:'',
myData:[],
now:-1 //當前選中項的索引
},
methods:{
getData(e){
//如果按方向鍵上、下,則不發請求
if(e.keyCode==38||e.keyCode==40)
return;
this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
params:{
wd:this.keyword
},
jsonp:'cb'
}).then(resp => {
this.myData=resp.data.s;
});
},
changeDown(){
this.now++;
this.keyword=this.myData[this.now];
if(this.now==this.myData.length){
this.now=-1;
}
},
changeUp(){
this.now--;
this.keyword=this.myData[this.now];
if(this.now==-2){
this.now=this.myData.length-1;
}
}
}
});
}
</script>
</head>
<body>
<div id="itany">
<input type="text" v-model="keyword" @keyup="getData($event)" @keydown.down="changeDown" @keydown.up.prevent="changeUp">
<ul>
<li v-for="(value,index) in myData" :class="{current:index==now}">
{{value}}
</li>
</ul>
<p v-show="myData.length==0">暫無數據....</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue生命週期</title>
<script src="js/vue.js"></script>
<script>
window.οnlοad=function(){
let vm=new Vue({
el:'#itany',
data:{
msg:'welcome to itany'
},
methods:{
update(){
this.msg='歡迎來到南京網博!';
},
destroy(){
// this.$destroy();
vm.$destroy();
}
},
/* beforeCreate(){
alert('組件實例剛剛創建,還未進行數據觀測和事件配置');
},
created(){ //常用!!!
alert('實例已經創建完成,並且已經進行數據觀測和事件配置');
},
beforeMount(){
alert('模板編譯之前,還沒掛載');
},
mounted(){ //常用!!!
alert('模板編譯之後,已經掛載,此時纔會渲染頁面,才能看到頁面上數據的展示');
},
beforeUpdate(){
alert('組件更新之前');
},
updated(){
alert('組件更新之後');
},
beforeDestroy(){
alert('組件銷燬之前');
},
destroyed(){
alert('組件銷燬之後');
} */
});
}
</script>
</head>
<body>
<div id="itany">
{{msg}}
<br>
<button @click="update">更新數據</button>
<button @click="destroy">銷燬組件</button> //銷燬組件將無法進行更新了
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>計算屬性</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="itany">
<!--
1.基本用法
-->
<h2>{{msg}}</h2>
<h2>{{msg2}}</h2>
<!-- 對數據處理再顯示 -->
<h2>{{msg.split(' ').reverse().join(' ')}}</h2>
<h2>{{reverseMsg}}</h2>
<button @click="change">修改值</button>
<!--
2.計算屬性 vs 方法
-->
<h2>{{num1}}</h2>
<h2>{{num2}}</h2>
<h2>{{getNum2()}}</h2>
<button οnclick="fn()">測試</button>
<!--
3.get和set
-->
<h2>{{num2}}</h2>
<button @click="change2">修改計算屬性</button>
</div>
<script>
var vm=new Vue({
el:'#itany',
data:{ //普通屬性
msg:'welcome to itany',
num1:8
},
computed:{ //計算屬性
msg2:function(){ //該函數必須有返回值,用來獲取屬性,稱爲get函數
return '歡迎來到南京網博';
},
reverseMsg:function(){
//可以包含邏輯處理操作,同時reverseMsg依賴於msg
return this.msg.split(' ').reverse().join(' ');
},
num2:{
get:function(){ //默認會調用此方法
console.log('num2:'+new Date());
return this.num1-1;
},
set:function(val){ //當值被修改過後會調用
console.log('修改num2值');
// this.num2=val;
this.num1=250;
}
}
},
methods:{
change(){
this.msg='i love you';
//this.num1=666;
},
getNum2(){
console.log(new Date());
return this.num1-1;
},
change2(){
this.num2=111;
}
}
});
function fn(){
setInterval(function(){
// console.log(vm.num2);
console.log(vm.getNum2());
},1000);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue實例的屬性和方法</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="itany">
{{msg}}
<h2 ref="hello">你好</h2>
<p ref="world">世界</p>
<hr>
<h1 ref="title">標題:{{name}}</h1>
</div>
<script>
var vm=new Vue({
el:'#itany',
data:{
msg:'welcome to itany'
},
name:'tom',
age:24,
show:function(){
console.log('show');
}
});
/**
* 屬性
*/
//vm.屬性名 獲取data中的屬性
console.log(vm.msg);
//vm.$el 獲取vue實例關聯的元素
console.log(vm.$el); //DOM對象
vm.$el.style.color='red';
//vm.$data //獲取數據對象data
console.log(vm.$data);
console.log(vm.$data.msg);
//vm.$options //獲取自定義屬性
console.log(vm.$options.name);
console.log(vm.$options.age);
vm.$options.show();
//vm.$refs 獲取所有添加ref屬性的元素
console.log(vm.$refs);
console.log(vm.$refs.hello); //DOM對象
vm.$refs.hello.style.color='blue';
/**
* 方法
*/
//vm.$mount() 手動掛載vue實例
// vm.$mount('#itany');
var vm=new Vue({
data:{
msg:'歡迎來到南京網博',
name:'tom'
}
}).$mount('#itany');
//vm.$destroy() 銷燬實例
// vm.$destroy();
// vm.$nextTick(callback) 在DOM更新完成後再執行回調函數,一般在修改數據之後使用該方法,以便獲取更新後的DOM
//修改數據
vm.name='湯姆';
//DOM還沒更新完,Vue實現響應式並不是數據發生改變之後DOM立即變化,需要按一定的策略進行DOM更新,需要時間!!
// console.log(vm.$refs.title.textContent);
vm.$nextTick(function(){
//DOM更新完成,更新完成後再執行此代碼
console.log(vm.$refs.title.textContent);
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加和刪除屬性:$set、$delete</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="itany">
<button @click="doUpdate">修改屬性</button>
<button @click="doAdd">添加屬性</button>
<button @click="doDelete">刪除屬性</button>
<hr>
<h2>{{user.name}}</h2>
<h2>{{user.age}}</h2>
</div>
<script>
var vm=new Vue({
el:'#itany',
data:{
user:{
id:1001,
name:'tom'
}
},
methods:{
doUpdate(){
this.user.name='湯姆'
},
doAdd(){
// this.user.age=25; //通過普通方式爲對象添加屬性時vue無法實時監視到
// this.$set(this.user,'age',18); //通過vue實例的$set方法爲對象添加屬性,可以實時監視
// Vue.set(this.user,'age',22);
if(this.user.age){
this.user.age++;
}else{
Vue.set(this.user,'age',1);
}
// console.log(this.user);
},
doDelete(){
if(this.user.age){
// delete this.user.age; //無效
Vue.delete(this.user,'age');
}
}
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>監視數據的變化:$watch</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="itany">
<input type="text" v-model="name">
<h3>{{name}}</h3>
<hr>
<input type="text" v-model="age">
<h3>{{age}}</h3>
<hr>
<input type="text" v-model="user.name">
<h3>{{user.name}}</h3>
</div>
<script>
var vm=new Vue({
el:'#itany',
data:{
name:'tom',
age:23,
user:{
id:1001,
name:'alice'
}
},
watch:{ //方式2:使用vue實例提供的watch選項
age:(newValue,oldValue) => {
console.log('age被修改啦,原值:'+oldValue+',新值:'+newValue);
},
user:{
handler:(newValue,oldValue) => {
console.log('user被修改啦,原值:'+oldValue.name+',新值:'+newValue.name);
},
deep:true //深度監視,當對象中的屬性發生變化時也會監視
}
}
});
//方式1:使用vue實例提供的$watch()方法
vm.$watch('name',function(newValue,oldValue){
console.log('name被修改啦,原值:'+oldValue+',新值:'+newValue);
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>自定義指令</title>、
<script src="js/vue.js"></script>
</head>
<body>
<!-- <div id="itany">
<h3 v-hello>{{msg}}</h3>
<button @click="change">更新數據</button> -->
<h3 v-world:wbs17022.hehe.haha="username">{{msg}}</h3>
<p v-world>網博,專業的前端培訓</p>
<h3 v-wbs>網博</h3>
<input type="text" v-model="msg" v-focus>
</div>
<script>
/**
* 自定義全局指令
* 主:使用指令時必須在指定名稱前加前綴v- 即v-指令名稱
*/
Vue.directive('hello',{
bind(){//常用
alert("指令第一次綁定到元素上時調用,只調用一次,可執行初始化操作");
},
inserted(){
alert('被綁定元素插入到dom中時調用');
},
update(){
alert("被綁定元素所在模板更新時調用");
},
componentUpdated(){
alert('被綁定元素所在模板完成一次更新週期時調用');
},
unbind(){
alert('指令與元素解綁時調用,只調用一次');
}
});
//鉤子函數
Vue.directive('world',{
bind(el,binding){
console.log(el); //指令綁定的元素,Dom對象
el.style.color='red';
console.log(binding); *///name
}
});
//傳入一個簡單的函數 ,bind和update 時調用
Vue.directive('wbs',function(){
alert('wbs17022');
});
var vm = new Vue({
el:'#itany',
data:{
msg:'welcome to ma an shan',
username:'alice'
},
methods:{
change(){
this.msg='歡迎來到馬鞍山'
}
},
deactivated:{//自定義局部命令
focus:{
//當被綁定元素插入到Dom 中時 獲取焦點
inserted(el){
el.focus();
}
}
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>練習:自定義指令</title>
<script src="js/vue.js"></script>
<style>
#itany div{
width: 100px;
height: 100px;
position:absolute;
}
#itany .hello{
background-color:red;
top:0;
left:0;
}
#itany .world{
background-color:blue;
top:0;
right:0;
}
</style>
</head>
<body>
<div id="itany">
<div class="hello" v-drag>itany</div>
<div class="word" v-drag> 網博</div>
</div>
<script>
Vue.directive('drag',function(el){
el.οnmοusedοwn=function(e){
//獲取鼠標點擊處分別與div左邊和上邊的距離:鼠標位置-div位置
var disX=e.clientX-el.offsetLeft;
var disY=e.clientY-el.offsetTop;
console.log(disX,disY);
//包含在onmousedown裏面,表示點擊後才移動,爲防止鼠標移出div,使用document.onmousemove
document.οnmοusemοve=function(e){
//獲取移動後div的位置:鼠標位置-disX/disY
var l=e.clientX-disX;
var t=e.clientY-disY;
el.style.left=l+'px';
el.style.top=t+'px';
}
//停止移動
document.οnmοuseup=function(e){
document.οnmοusemοve=null;
document.οnmοuseup=null;
}
}
});
var vm=new Vue({
el:'#itany',
data:{
msg:'welcome to itany',
username:'alice'
},
methods:{
change(){
this.msg='歡迎來到南京網博'
}
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>動畫</title>
<script src="js/vue.js"></script>
<style>
p{
width: 300px;
height: 300px;
background-color:red;
}
.fade-enter-active,.fade-leave-active{
transition:all 3s ease;
}
.fade-enter-active{
opacity:1;
width:300px;
height:300px;
}
.fade-leave-active{
opacity:0;
width:50px;
height:50px;
}
/* .fade-enter需要放在.fade-enter-active的後面 */
.fade-enter{
opacity:0;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="itany">
<button @click="flag=!flag">點我</button>
<transition name="fade"
@before-enter="beforeEnter"
@enter="enter"
@after-enter="afterEnter"
@before-leave="beforeLeave"
@leave="leave"
@after-leave="afterLeave"
>
<p v-show="flag">網博</p>
</transition>
</div>
<script>
var vm=new Vue({
el:'#itany',
data:{
flag:false
},
methods:{
beforeEnter(el){
// alert('動畫進入之前');
},
enter(){
// alert('動畫進入');
},
afterEnter(el){
// alert('動畫進入之後');
el.style.background='blue';
},
beforeLeave(){
// alert('動畫即將之前');
},
leave(){
// alert('動畫離開');
},
afterLeave(el){
// alert('動畫離開之後');
el.style.background='red';
}
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>動畫</title>
<link rel="stylesheet" href="css/animate.css">
<script src="js/vue.js"></script>
<style>
p{
width: 300px;
height: 300px;
background-color:red;
margin:0 auto;
}
</style>
</head>
<body>
<div id="itany">
<button @click="flag=!flag">點我</button>
<transition enter-active-class="animated fadeInLeft" leave-active-class="animated fadeOutRight">
<p v-show="flag">網博</p>
</transition>
</div>
<script>
var vm=new Vue({
el:'#itany',
data:{
flag:false
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多元素動畫</title>
<link rel="stylesheet" href="css/animate.css">
<script src="js/vue.js"></script>
<style>
p{
width: 100px;
height: 100px;
background-color:red;
margin:20px auto;
}
</style>
</head>
<body>
<div id="itany">
<button @click="flag=!flag">點我</button>
<transition-group enter-active-class="animated bounceInLeft" leave-active-class="animated bounceOutRight">
<p v-show="flag" :key="1">itany</p>
<p v-show="flag" :key="2">網博</p>
</transition-group>
</div>
<script>
var vm=new Vue({
el:'#itany',
data:{
flag:false
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>練習:多元素動畫</title>
<link rel="stylesheet" href="css/animate.css">
<script src="js/vue.js"></script>
<style>
p{
width: 100px;
height: 100px;
background-color:red;
margin:20px auto;
}
</style>
</head>
<body>
<div id="itany">
<input type="text" v-model="name">
<transition-group enter-active-class="animated bounceInLeft" leave-active-class="animated bounceOutRight">
<p v-for="(v,k) in arr2" :key="k">
{{v}}
</p>
</transition-group>
</div>
<script>
var vm=new Vue({
el:'#itany',
data:{
flag:true,
arr:['tom','jack','mike','alice','alex','mark'],
name:''
},
computed:{
arr2:function(){
var temp=[];
this.arr.forEach(val => {
if(val.includes(this.name)){
temp.push(val);
}
});
return temp;
}
}
});
</script>
</body>
</html>