Vue实战

写在前面
  你们好,我是小庄。很高兴能和你们一起学习Vue。如果您对Java感兴趣的话可关注我的动态.
  写博文是一种习惯,在这过程中能够梳理和巩固知识点。

一、基础入门

1、初学vue.js

1)、可以使用自己下载好的vue.js

2)、使用csdn的vue.js

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

3)、基础案例

el - - > 挂载点

<div id="app">
  {{ message }}
</div>

<script>
    //可以使用选择器,class使用“.”等等,都是支持的
var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})
</script>

2、小试牛刀

1)、数据类型

<div id="app">
  {{ message }}
    <span>{{ user.name }}</span><!-- 获取对象的属性-->
    <ul>
        <li>{{ aihao[0] }}</li><!-- 获取数组的值 -->
    </ul>
</div>

<script>
    //可以使用选择器,class使用“.”等等,都是支持的
    var app = new Vue({
        el: '#app',
        data: {
            message: 'Hello Vue!',
            user:{
                name:"zhangsan",
                ago:18,
                sex:"男"
            },
            aihao:["篮球","羽毛球","排球"]
        }
    })
</script>

3、指令的使用

1.v-text

介绍:使用时会覆盖元素之前的信息

基本使用

<div id="app">
    <h2 v-text="message">程序员</h2><!--这里的“程序员”会被覆盖-->
    <!--如果想使用在内部,需要使用插值表达式-->
	<h2>程序员{{message}}</h2>
</div>
<script>
	var app=new Vue({
        el:"#app",
        data:{
            message:"Hello Vue!"
        }
    })
</script>
2.v-html

提示:如果是普通文本,则和v-text没有区别,如果是的标签,需要渲染,则使用v-html

<div id="app">
    <!--可查看区别-->
    <h2 v-text="message"></h2>
    <h2 v-html="message"></h2>
</div>
<script>
	var app=new Vue({
        el:"#app",
        data:{
            message:"<a href="https://cn.vuejs.org/">vue学习</a>"
        }
    })
</script>
3.v-on
  • 作用是:为元素绑定事件

  • 事件名不需要写on

  • 指令可以简写为@

  • 可以传参

  • 事件的后面跟上.修饰符可以对事件进行限制

  • .enter可以限制触发的按键为回车

    代码演示

<div id="app">
    <input type="button" value="v-on指令" v-on:click="update"/>
 <!--  <input type="button" value="v-on指令" @click="update"/> -->
	<p v-text="food"></p>
   <input type="text" @keyup.enter="submit">
<script>
var app=new Vue({
    el:"#app",
    data:{
        food:"大白菜"
        
    },
    methods:{//用于做事件处理的属性
    update:function(){
   this.food="小白菜";
}
    submit:function(){
    alert('提交成功');
}
},
})
</script>
4.v-show

根据表达式的真假,切换元素的显示和隐藏

主要对display:none属性进行处理

案例演示

<div id="app">
    <input type="button" value=“切换显示状态 @click="changenShow">
    <h1 v-show="show">
        {{message}}
    </h1>
	
	<h1 v-show="age>16">
	    {{message}}
	</h1>
</div>
		
<script>
var app=new Vue({
    el:"#app",
    data:{
        show:true,
        message:"我显示在这",
		age:17
    },
    methods:{
    changenShow:function(){
    this.show=!this.show;
}
}
})
</script>
5.v-if

根据表达式的真假,切换元素的显示和隐。功能和v-show类似,这个是对标签的删除,以下删除掉h1标签

频繁切换用v-show

案例演示

<div id="app">
    <input type="button" value=“切换显示状态 @click="changenShow">
    <h1 v-if="show">
        {{message}}
    </h1>
	
	<h1 v-if="age>16">
	    {{message}}
	</h1>
</div>
		
<script>
var app=new Vue({
    el:"#app",
    data:{
        show:true,
        message:"我显示在这",
		age:17
    },
    methods:{
    changenShow:function(){
    this.show=!this.show;
}
}
})
</script>
6.v-bind

设置元素的属性(eg:src,title,class)

<!-- css样式-->
<style>
			.active{
				border:1px solid red;
			}
		</style>

<div id="app">
    <img v-bind:src="imgSrc">
    <img :src="imgSrc" :title="imgTitle" :class="{active:isActive}" @click="changActive">//active是css样式
</div>
<script>
	var app=new Vue({
        el:"#app",
        data:{
            imgSrc:"../img/1.gif",
            imgTitle:"图片",
            isActive:true
        },
        methods:{
            changActive:function(){
                this.isActive=!this.isActive;
            }
        }
        
    })
</script>
7.图片切换案例
<script src="../js/vue.js"></script>
<div id="app" class="box">
	<input type="button" value="" v-show="index!=0" @click="less"/>
    <img :src="imgSrc[index]" width="400" height="300">
	<input type="button" value="" v-show="index<imgSrc.length-1" @click="add"/>
</div>
<script>
	var app=new Vue({
        el:"#app",
        data:{
            imgSrc:[
				"../img/1.gif",
				"../img/2.jpg",
				"../img/3.jpg"
			],
           index:0
        },
        methods:{
		
			
            add:function(){
				this.index++;
			},
			less:function(){
				this.index--;
			},
			
			//设置计时器
			fun:function(){
			    //setInterval(函数体,时间)
			    setInterval(this.play,2000)
			},
			play:function(){
			     this.index++;
			     if(this.index == this.imgSrc.length){
			           this.index = 0;
			      }
			 }
        },
        mounted:function(){    //生命周期  钩子函数   挂载完成
            this.fun()
        }
    })
</script>
7.v-for

1、作用:根据数据生成列表结构

2、数组经常和v-for结合使用

3、语法是(item,index) in 数据//item表示变量,index表示索引

案例演示

<div id="app">
	<input type="button" value="添加数据" @click="add"/>
	<input type="button" value="删除数据" @click="remove"/>
	<ul>
		<li v-for="(item,index) in arr">
			{{index+1}}、{{item}}
		</li>
		<hr />
		<li v-for="item in arr">
			{{item}}
		</li>
		<hr />
		<h2 v-for="item in user">{{item.name}}</h2>
	</ul>
</div>
<script>
	var app=new Vue({
        el:"#app",
        data:{
            arr:["篮球","兵乓球","羽毛球","排球"],
			user:[{name:"张三"},{name:"李四"}
				],
           index:0
        },
		methods:{
			add:function(){
				this.user.push({name:"6666666666"})
			},
			remove:function(){
				this.user.pop();
			}
		}
    })
</script>
8、v-model

获取和设置表单元素的值(双向数据绑定)

1、作用:便捷的设置和获取表单元素的值

2、绑定的数据会和表单元素值相关联

3、绑定的数据和表单元素的值是双向数据绑定

案例演示

<div id="app">
	
	<input type="text" v-model="message" @keyup.enter="getMessage"/>
	<h1>{{ message}}</h1>
</div>
<script>
	var app=new Vue({
        el:"#app",
        data:{
           message:"你好啊"
        },
		methods:{
		getMessage:function(){
			var msg=this.message;
			console.log(msg);
		}
		}
    })
</script>

4.axios+Vue

导入js

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
1.get请求发送数据
<script>
   //方法一
var params = {
               locale: 1,
             };
             // 向具有指定ID的用户发出请求
axios.get('/user?ID=12345').then(function (response) { 
    //get()内,是发送的请求的url,response是响应的内容,这里和Jquery Ajax响应的内容有区别
    console.log(response);
                }).catch(function (error) {
    			//打印错误信息
                  console.log(error);
             });
    //方法二
axios.get('/user',{params:params}).then(function (res) {
                console.log(res)
            }).catch(function (err) {
               console.log(err);
           })  
    
</script>
2.post请求发送数据
<script>
    //方法一
    axios.post('/url', {
                   sex: '1',
                   age: '2'}).then(function (res) {
                       console.log(res);
                   })
                    .catch(function (error) {
                        console.log(error);
    });
    //方法二
    axios.post("../package.json",{
        userId:"888"
    },{
        headers:{
            token:"tom"
        }
    }).then(res=>{
        this.msg = res.data;
    }).catch(function (error) {
        console.log(error);
    })
</script>
3.get和post的区别
<script>
axios({
      url:"../package.json",
      // method:"get",
      method:"post",
      data:{
        userId:"101"
        },
      // params:{
      //   userId:"102"
      // },
      headers:{
        token:"http-test"
      }
      }).then(res=>{
      this.msg = res.data;
      })
</script>
//如果methods是post方式的话,就要用 data:{ userId:"101" },传入参数,如果是get请求的话,用params

5.天气查询系统案例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>天气预报</title>
		<style>
		
		.search_form{
			position: relative;
			width:35%;
			height:42px;
			margin: auto;
			margin-bottom:20px;
		}
		
		/*左边输入框设置样式*/
		.input_text{
			width:80%;
			height: 40px;
			border:1px solid green;
			/*清除掉默认的padding*/
			padding:0px;
			
			/*提示字首行缩进*/
			text-indent: 10px;
		
			/*去掉蓝色高亮框*/
			outline: none;
		
			/*用浮动解决内联元素错位及小间距的问题*/
			float:left;
		}
		
		.input_sub{
			width:18%;
			height: 42px;
			background: green;
		
			/*去掉submit按钮默认边框*/
			border:0px;
			/*改成右浮动也是可以的*/
			float:left;
			color:white;/*搜索的字体颜色为白色*/
			cursor:pointer;/*鼠标变为小手*/
		}
		.weather{
			position: relative;
			top: 25px;
			width: 60%;
			margin: auto;
			list-style: none;
		}
		.list{
			width: 36%;
			margin: auto; 
			position: relative;
			top: -1.5em;
		}
		.list p{
			position: relative;
			margin-left: 10px;
			cursor:pointer;
			float: left;
		}
		
		.one{
			float: left;
			height: 240px;
			width: 19%;
			text-align: center;
			border: 1px solid #A5A5A5;
		}
		.clear{ clear:both} 
		#joke{
			width: 80%;
			margin: auto;
			text-align: center;
			
		}
	
		</style>
	</head>
	<body>

<script src="../js/vue.js"></script>
<script src="../js/jquery-3.3.1.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
		<h1 style="text-align: center;">天气预报</h1>
		<div class="search_form">
			<input type="text"  @keyup.enter="searcjWeather" v-model="city" class="input_text" placeholder="请输入城市名称" @blur="noshow">

			<input type="button" value="查询" class="input_sub" @click="inquire">
		</div>
		<div class="list">
			<p @click="region('北京')">北京</p>
			<p @click="region('上海')">上海</p>
			<p @click="region('广州')">广州</p>
			<p @click="region('深圳')">深圳</p>
		</div>
		<div class="clear"></div>
		<p v-show="city.length==0"  style="position: relative;top: -2em; width: 35%; margin: auto; color: #93dddd;">{{message}}</p>
		<p v-show="error.length!=0"  style="position: relative;top: -2em; width: 35%; margin: auto; color: darkred;">{{error}}</p>
		<ul class="weather">
			<li v-for="item in tianQiArr" class="one" v-show="city.length!=0" >
				<h2  style="color: #aaaa00;" >{{crity}}</h2>
					<h1 style="color: #ffaa00;" >{{item.type}}</h1>

					<h4 style="color: #ffaa00;" >{{item.low}}~{{item.high}}</h4>
					<p style="color: #4A956E; font-weight: bold;" >{{item.date}}</p>
			</li>
		</ul>



		<div class="clear"></div>
		<p id="joke" v-show="city.length!=0" v-if="show" style="position: relative;top: 3.5em;"><strong>笑话:</strong>{{joke}}</p>

	</div>

	<script>
		var app= new Vue({
			//建立挂载点
			el: "#app",
			data:{
				//显示内容
				message:"输入的内容不能为空",
				//存放笑话内容
				joke:"",
				//创建城市名称
				city:"",
				error:"",
				show:false,
				crity:"",
				//存储请求过来天气的值
				tianQiArr:[]
			},
			methods: {

				searcjWeather:function(){
					//保存this,在回调函数里this值会变动,所以需要保存
					var that=this;
					this.crity=this.city;
					if(that.city.length!=0){
						axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city).then(function(response){
							that.tianQiArr=response.data.data.forecast;
							that.crity=response.data.data.city;
							$.get("https://autumnfish.cn/api/joke", function(result){
								that.joke=result;
								that.error="";
								that.show=true;
							});

						}).catch(function(error){
							that.show=false;
							that.error="输入的城市错误";
							that.tianQiArr=0;


						})

					}
					else {
						that.message="输入的内容不能为空";
						that.tianQiArr=0;
						that.show=false;
					}
				},
				region:function(e){
					//这里是城市标签,将值直接传入给当前的city,传入完毕并调用函数
					this.city=e;
					//调用函数
					this.searcjWeather();
				},
				inquire:function(){
					//点击查询按钮,调用函数
					this.searcjWeather();
				},
				noshow:function(){
					this.error="";
				}

			}
		})

	</script>
	</body>
</html>
喜欢的小伙伴记得点关注哦
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值