vue基礎知識練習整理2

1、發送AJAX請求php

<div id="demo1">
		<button @click="send">發送AJAX請求</button>
		<button @click="sendGet">GET方式發送AJAX請求</button>
		<button @click="sendPost">POST方式發送AJAX請求</button>
		<hr>
		<br>
		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>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script src="js/vue-resource.min.js"></script>
<script>
	let vm = new Vue({
       el:'#demo1', 
       data:{
			user:{
				// name:'alice',
				// age:19
			},
			uid:''
		},
       methods:{
			send(){
				axios({
					method:'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);
						});
					},
			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>

2、發送AJAX請求2css

<div id="demo1">
		<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>

		.current{
			background-color:#ccc;
		}
	</style>
<script src="js/vue.js"></script>
<script src="js/vue-resource.min.js"></script>
<script>
	let vm = new Vue({
       el:'#demo1', 
       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>

3、Vue生命週期前端

<div id="demo1">
		{{msg}}
		<br>

		<button @click="update">更新數據</button>
		<button @click="destroy">銷燬組件</button>
</div>
<script src="js/vue.js"></script>
<script>
	let vm=new Vue({
				el:'#demo1',
				data:{
					msg:'welcome to demo1'
				},
				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>

4、計算屬性vue

<div id="demo1">
		<!-- 
			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 onclick="fn()">測試</button>
		
		<!-- 3.get和set -->
		 <h2>{{num2}}</h2>
		 <button @click="change2">修改計算屬性</button>

	</div>
<script src="js/vue.js"></script>
<script>
		var vm=new Vue({
			el:'#demo1',
			data:{ //普通屬性
				msg:'welcome to demo1',
				num1:8
			},
			computed:{ //計算屬性
				msg2:function(){ //該函數必須有返回值,用來獲取屬性,稱爲get函數
					return '歡迎來到vue';
				},
				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=111;
					}
				}
			},
			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>

5、vue實例的屬性和方法ios

<div id="demo1">
		{{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>

6、添加和刪除屬性:$set、$deletegit

<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 src="js/vue.js"></script>
<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>

7、監視數據的變化:$watchgithub

<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 src="js/vue.js"></script>
	<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>

8、自定義指令json

<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 src="js/vue.js"></script>
<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 itany',
				username:'alice'
			},
			methods:{
				change(){
					this.msg='歡迎來到南京網博'
				}
			},
			directives:{ //自定義局部指令
				focus:{
					//當被綁定元素插入到DOM中時獲取焦點
					inserted(el){
						el.focus();
					}
				}
			}
		});
	</script>

9、練習:自定義指令axios

<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>
<div id="itany">
		<div class="hello" v-drag>itany</div>
		<div class="world" v-drag>網博</div>
</div>
<script src="js/vue.js"></script>
	<script>
		Vue.directive('drag',function(el){
			el.onmousedown=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.onmousemove=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.onmouseup=function(e){
					document.onmousemove=null;
					document.onmouseup=null;
				}

			}
		});

		var vm=new Vue({
			el:'#itany',
			data:{
				msg:'welcome to itany',
				username:'alice'
			},
			methods:{
				change(){
					this.msg='歡迎來到南京網博'
				}
			}
		});
	</script>

10、動畫api

<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>
	<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 src="js/vue.js"></script>
	<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>

11、動畫2

<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>
<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>

12、多元素動畫

<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>
<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>

十3、練習:多元素動畫

<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>

<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-show="flag">
				{{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>
相關文章
相關標籤/搜索