• 11.vue 数据交互


    vue

    new Vue({
    	el,选择器  string/obj  不能选择html/body
    	data,
    	methods,
    	template  string/obj
    	//生命周期 —— 虚拟DOM
    	1、初始化
    	beforeCreate
    	created
    	2、渲染
    	beforeMount
    	mounted
    	3、更新
    	beforeUpdate
    	updated
    	4、销毁
    	beforeDestroy
    	destroyed
    });
    

    指令:v-model/text/html/bind/for/if/show

    v-model 绑定数据 数据来源
    v-text 纯文本 简写 {{v-model/data}}

    bind 绑定属性
    v-bind:属性名="'值'" 简写 :属性名="'值'"

    v-bind="json/{...}"

    v-on:事件="事件函数 --- methods"
    @事件="事件函数"

    v-for="v,k,i in/of arr/json"

    v-show 样式
    v-if dom节点


    交互

    ajax   fetch   vue-resource   axios

    fetch使用方式

    get:
    fetch(url).then(res=>{
    	 return res.text()/res.json();
    }).then(data=>{
    		
    }).catch(err=>{
    
    });
    
    fetch(url).then(res=>{
    
    	if(res.ok){//true/false
    		res.text()/res.json().then(data=>{
    			
    		});
    	}
    }).catch(err=>{
    
    });
    
    
    res.text()/res.json();返回的都是promise对象
    

    exp:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <style>
    </style>
    <script>
    window.onload = function(){
    	
    	let oBtn = document.getElementById("btn1");
    	
    	oBtn.onclick = function(){
    		 
    		let url = "get.php?a=1&b=2";
    		
    		fetch(url).then(res=>{
    			return res.text();	
    		}).then(data=>{
    			console.log("get:",data);	
    		});
    		
    	};
    };
    </script>
    </head>
    
    <body>
    <div id="app">
    	 <input id="btn1" type="button" value="按钮">
    	 
    </div>
    </body>
    </html>
    
    post:
    fetch(url,{
    	method:"post",
    	headers:{
    		"content-type":"application/x-www-form-urlencoded"
    	},
    	body:"name=value&name=value"/ new URLSearchParams()
    })
    

    exp:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <style>
    </style>
    <script>
    window.onload = function(){
    	
    	let oBtn = document.getElementById("btn1");
    	
    	oBtn.onclick = function(){
    		 
    		let url = "post.php";//?a=1&b=2
    		
    		fetch(url,{
    			method:"post",	
    			headers:{
    				"content-type":"application/x-www-form-urlencoded"
    			},
    			body:"a=1&b=2"
    		}).then(res=>{
    			return res.text();	
    		}).then(data=>{
    			console.log("post:",data);	
    		});
    		
    	};
    };
    </script>
    </head>
    
    <body>
    <div id="app">
    	 <input id="btn1" type="button" value="按钮">
    	 
    </div>
    </body>
    </html>
    

    fech跨域

    https://www.npmjs.com/package/fetch-jsonp

    exp:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <style>
    </style>
    <script src="fetch-jsonp.js"></script>
    <script>
    window.onload = function(){
    	
    	let oBtn = document.getElementById("btn1");
    	
    	oBtn.onclick = function(){
    		let url = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=aaa";
    		 
    	  fetchJsonp(url,{
        		jsonpCallback: 'cb',
    			jsonpCallbackFunction: 'xxx'
    	  }).then(function(res) {
    		return res.json()
    	  }).then(function(json) {
    		console.log('parsed json', json)
    	  }).catch(function(err) {
    		console.log('parsing failed', err)
    	  })
    			
    	};
    };
    </script>
    </head>
    
    <body>
    <div id="app">
    	 <input id="btn1" type="button" value="按钮">
    	 
    </div>
    </body>
    </html>
    

    vue-resource/axios

    get:
    vm.$http.get(url,{params:{}}).then(res=>{
    	
    	 res.body/bodyText/data
    
    }).catch;
    
    post:
    vm.$http.post(url,{},{emulateJSON:true}).then(res=>{
    	
    	 res.body/bodyText/data
    
    }).catch;
    
    jsonp:
    vm.$http.jsonp(url,{params:{},jsonp:"cb"}).then(res=>{
    	
    	 res.body/bodyText/data
    
    }).catch;
    

    exp:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <script src="vue.js"></script>
    <script src="vue-resource.js"></script>
    <script>
    window.onload = function(){
    	let vm = new Vue({
    		el:"#app",
    		data:{
    				
    		},
    		methods:{
    			get(){
    				//get(url,{params:{xxx}}).then.catch;
    				let url = "get.php"
    				this.$http.get(url,{params:{a:1,b:1}}).then(res=>{
    					//res.body/bodyText/data
    					console.log(1,res.data);	
    				}).catch(err=>{
    					console.log(2,err);	
    				});
    			},
    			post(){
    				let url = "post.php"
    				this.$http.post(url,{a:1,b:1},{emulateJSON:true}).then(res=>{
    					//res.body/bodyText/data
    					console.log(1,res.data);	
    				}).catch(err=>{
    					console.log(2,err);	
    				}); 
    			},
    			jsonp(){
    				
    				let url = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su"
    				this.$http.jsonp(url,{params:{wd:"aaa"},jsonp:"cb"}).then(res=>{
    					//res.body/bodyText/data
    					console.log(1,res.data.s);	
    				}).catch(err=>{
    					console.log(2,err);	
    				}); 
    			}	
    		}
    	});
    };
    </script>
    </head>
    
    <body>
    <div id="app">
    	<input @click="get" type="button" value="get"/>
    	<input @click="post" type="button" value="post"/>
    	<input @click="jsonp" type="button" value="jsonp"/>
    </div>
    </body>
    </html>
    

    axios:

    get:
    axios.get(url,{params:{}}).then(res=>{
    	
    	 res.data
    
    }).catch;
    
    post:
    axios.post(url,{}/"name=value&name=value").then(res=>{
    	
    	 res.data
    
    }).catch;
    

    exp:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <script src="vue.js"></script>
    <script src="axios.js"></script>
    <script>
    window.onload = function(){
    	let vm = new Vue({
    		el:"#app",
    		data:{
    				
    		},
    		methods:{
    			get(){
    				//get(url,{params:{xxx}}).then.catch;
    				let url = "get.php";
    				axios.get(url,{params:{a:11,b:11}}).then(res=>{
    					console.log(1,res.data);
    				}).catch(err=>{
    					console.log(2,err);	
    				}); 
    			},
    			post(){
    				//let url = "post.php";
    				let url = "http://localhost:3000/"
    				axios.post(url,{a:1,b:2}).then(res=>{
    				//axios.post(url,"a=11&b=11").then(res=>{
    					console.log(1,res.data);
    				}).catch(err=>{
    					console.log(2,err);	
    				}); 
    				 
    			}
    		}
    	});
    };
    </script>
    </head>
    
    <body>
    <div id="app">
    	<input @click="get" type="button" value="get"/>
    	<input @click="post" type="button" value="post"/>
    </div>
    </body>
    </html>
    
    跨域:
    推荐用模块 cors

    https://www.npmjs.com/package/cors

    app.use(cors());

    exp:
    app.js:

    var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var logger = require('morgan');
    var cors = require('cors')
    
    var indexRouter = require('./routes/index');
    var usersRouter = require('./routes/users');
    
    var app = express();
    
    app.use(cors());
    /*app.use(function(req,res,next){
    	res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
        res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        res.header("X-Powered-By",' 3.2.1')
    	next();	
    });*/
    
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    
    app.use(logger('dev'));
    
    app.use(express.json());
    app.use(express.urlencoded({ extended: false }));
    
    
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    app.use('/', indexRouter);
    app.use('/users', usersRouter);
    
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      next(createError(404));
    });
    
    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
    
      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });
    
    module.exports = app;
    

    index.js:

    var express = require('express');
    var router = express.Router();
    
    /* GET home page. */
    router.post('/', function(req, res, next) {
    	console.log(req.body);
    	let {a,b} = req.body;
      	res.send({type:"post",res:a + b});
    });
    
    module.exports = router;
    

    案例:

    微博评论:

    1、weibo_axios.html:

    axios交互:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>微博ajax接口测试</title>
    <link href="style/weibo.css" rel="stylesheet" />
    <script src="vue.js"></script>
    <script src="axios.js"></script>
    <script>
    window.onload = function(){
    	let url = "weibo.php";
    	let vm = new Vue({
    		el:".app",
    		data:{
    			iNow:1,
    			msg:"abc",
    			arr:[],
    			pageCount:1,
    		},
    		methods:{
    			formatTime(iS){
    				let oDate = new Date(iS*1000);
    				return [
    					oDate.getFullYear(),"年",
    					oDate.getMonth()+1,"月",
    					oDate.getDate(),"日",
    					" ",
    					oDate.getHours(),"时",
    					oDate.getMinutes(),"分",
    					oDate.getSeconds(),"秒"
    				].join("")
    			},
    			/*weibo.php?act=add&content=xxx	添加一条
    				返回:{error:0, id: 新添加内容的ID, time: 添加时间}
    			*/
    			addMsg(){
    				axios.get(url,{params:{act:"add",content:this.msg}}).then(res=>{
    					console.log(res);	
    					this.getPageData(this.iNow);
    					this.getPageCount();
    				});		
    			},	
    			
    			/*weibo.php?act=get&page=1		获取一页数据
    			返回:[{id: ID, content: "内容", time: 时间戳, acc: 顶次数, ref: 踩次数}, {...}, ...]*/
    			getPageData(page){
    				this.iNow = page;
    				axios.get(url,{params:{act:"get",page}}).then(res=>{
    					//console.log(res);	
    					this.arr = res.data;
    				});	
    			},
    			/*weibo.php?act=get_page_count	获取页数
    				返回:{count:页数}*/
    			getPageCount(){
    				axios.get(url,{params:{act:"get_page_count"}}).then(res=>{
    					console.log(res.data.count);
    					this.pageCount = res.data.count;	
    				});	
    			},
    			/*weibo.php?act=del&id=12			删除一条数据
    				返回:{error:0}*/
    			del(id){
    				axios.get(url,{params:{act:"del",id}}).then(res=>{
    					console.log(res.data);	
    					this.getPageData(this.iNow);
    					this.getPageCount();
    				});	
    			},	
    			/*weibo.php?act=acc&id=12			顶某一条数据
    				返回:{error:0}*/
    			acc(item){
    				let id = item.id;
    				axios.get(url,{params:{act:"acc",id}}).then(res=>{
    					console.log(res.data);
    					
    					if(res.data.error == 0){//顶成功了
    						item.acc++;
    						console.log(item.acc);
    					}
    					
    				});	
    			},
    			ref(item){}	
    			
    		}
    	});
    	
    	vm.getPageData(vm.iNow);
    	vm.getPageCount();
    };
    </script>
    </head>
    
    <body>
    <div class="app">
    <!--留言-->
         <div class="takeComment">
            <textarea v-model="msg" name="textarea" class="takeTextField" id="tijiaoText"></textarea>
            <div class="takeSbmComment">
                <input @click="addMsg" id="btn_send" type="button" class="inputs" value="" />
            </div>
        </div>
    <!--已留-->
        <div class="commentOn">
            <div class="noContent" v-show="arr.length==0">暂无留言</div>
            <div id="messList" class="messList">
            	<div class="reply" v-for="item in arr">
                    <p class="replyContent">{{item.content}}</p>
                    <p class="operation">
                        <span class="replyTime">{{formatTime(item.time)}}</span>
                        <span class="handle">
                        	<a href="javascript:;" class="top" @click="acc(item)">{{item.acc}}</a>
                            <a href="javascript:;" class="down_icon" @click="ref(item.id)">{{item.ref}}</a>
                            <a href="javascript:;" class="cut" @click="del(item.id)">删除</a>
                        </span>
                    </p>
                </div>
            </div>
            <div id="page" class="page">
            	<a @click="getPageData(item)" v-for="item in pageCount" href="javascript:;" :class="iNow==item?'active':''">{{item}}</a>
            	<!--<a href="javascript:;" class="active">1</a>
            	<a href="javascript:;">2</a>
            	<a href="javascript:;">3</a>-->
            </div>
        </div>
    </div>
    </body>
    </html>
    
    
    2、weibo_fetch.html:

    fetch交互

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<title>微博ajax接口测试</title>
    	<link href="style/weibo.css" rel="stylesheet" />
    	<script src="vue.js"></script>
    	<script>
    		window.onload = function(){
    			let url = "weibo.php";
    			let vm = new Vue({
    				el:".app",
    				data:{
    					iNow:1,
    					msg:"abc",
    					arr:[],
    					pageCount:1,
    				},
    				methods:{
    					formatTime(iS){
    						let oDate = new Date(iS*1000);
    						return [
    							oDate.getFullYear(),"年",
    							oDate.getMonth()+1,"月",
    							oDate.getDate(),"日",
    							" ",
    							oDate.getHours(),"时",
    							oDate.getMinutes(),"分",
    							oDate.getSeconds(),"秒"
    						].join("")
    					},
    					/*weibo.php?act=add&content=xxx	添加一条
    						返回:{error:0, id: 新添加内容的ID, time: 添加时间}
    					*/
    					addMsg(){
    						fetch(url+'?act=add&content='+this.msg).then(res=>{
    							console.log(1,res);
    							return res.json();
    							}).then(res=>{	
    							console.log(2,res);
    							this.getPageData(this.iNow);
    							this.getPageCount();
    						});		
    					},	
    					/*weibo.php?act=get&page=1		获取一页数据
    					返回:[{id: ID, content: "内容", time: 时间戳, acc: 顶次数, ref: 踩次数}, {...}, ...]*/
    					getPageData(page){
    						this.iNow = page;
    						fetch(url+"?act=get&page="+page).then(res=>{
    							return res.json();
    							}).then(res=>{	
    							console.log(3,res);	
    							this.arr = res;
    						});	
    					},
    					/*weibo.php?act=get_page_count	获取页数
    					返回:{count:页数}*/
    					getPageCount(){
    						fetch(url+"?act=get_page_count").then(res=>{
    							return res.json();
    							}).then(res=>{
    							console.log(4,res);
    							this.pageCount = res;	
    						});	
    					},
    
    					/*weibo.php?act=del&id=12			删除一条数据
    					返回:{error:0}*/
    					del(id){
    						let that = this;
    						fetch(url+"?act=del&id="+id).then(res=>{
    							return res.json();
    							}).then(res=>{
    							console.log(res);	
    							that.getPageData(that.iNow);
    							that.getPageCount();
    						});	
    					},	
    
    					/*weibo.php?act=acc&id=12			顶某一条数据
    					返回:{error:0}*/
    					acc(item){
    						let id = item.id;
    						fetch(url+"?act=acc&id="+id).then(res=>{
    							return res.json();
    							}).then(res=>{
    							console.log(res);
    							
    							if(res.error == 0){//顶成功了
    								item.acc++;
    								console.log(item.acc);
    							}
    							
    						});	
    					},
    					/*weibo.php?act=ref&id=12			踩某一条数据
    					返回:{error:0}*/
    					ref(item){
    						let id = item.id;
    						fetch(url+"?act=ref&id="+id).then(res=>{
    							return res.json();
    							}).then(res=>{
    							console.log(res);
    							
    							if(res.error == 0){//踩成功了
    								item.ref++;
    								console.log(item.ref);
    							}
    							
    						});
    					}	
    				}
    			})
    			vm.getPageData(vm.iNow);
    			vm.getPageCount();
    		}
    	</script>
    	
    </head>
    <body>
    	<div class="app">
    <!--留言-->
         <div class="takeComment">
            <textarea v-model="msg" name="textarea" class="takeTextField" id="tijiaoText"></textarea>
            <div class="takeSbmComment">
                <input @click="addMsg" id="btn_send" type="button" class="inputs" value="" />
            </div>
        </div>
    <!--已留-->
        <div class="commentOn">
            <div class="noContent" v-show="arr.length==0">暂无留言</div>
            <div id="messList" class="messList">
            	<div class="reply" v-for="item in arr">
                    <p class="replyContent">{{item.content}}</p>
                    <p class="operation">
                        <span class="replyTime">{{formatTime(item.time)}}</span>
                        <span class="handle">
                        	<a href="javascript:;" class="top" @click="acc(item)">{{item.acc}}</a>
                            <a href="javascript:;" class="down_icon" @click="ref(item)">{{item.ref}}</a>
                            <a href="javascript:;" class="cut" @click="del(item.id)">删除</a>
                        </span>
                    </p>
                </div>
            </div>
            <div id="page" class="page">
            	<a @click="getPageData(item)" v-for="item in pageCount" href="javascript:;" :class="iNow==item?'active':''">{{item}}</a>
            	<!--<a href="javascript:;" class="active">1</a>
            	<a href="javascript:;">2</a>
            	<a href="javascript:;">3</a>-->
            </div>
        </div>
    </div>
    </body>
    </html>
    
    weibo.php
    <?php
    /*
    **********************************************
    	usage:
    			weibo.php?act=add&content=xxx	添加一条
    				返回:{error:0, id: 新添加内容的ID, time: 添加时间}
    			
    			weibo.php?act=get_page_count	获取页数
    				返回:{count:页数}
    			
    			weibo.php?act=get&page=1		获取一页数据
    				返回:[{id: ID, content: "内容", time: 时间戳, acc: 顶次数, ref: 踩次数}, {...}, ...]
    			
    			weibo.php?act=acc&id=12			顶某一条数据
    				返回:{error:0}
    			
    			weibo.php?act=ref&id=12			踩某一条数据
    				返回:{error:0}
    				
    			weibo.php?act=del&id=12			删除一条数据
    				返回:{error:0}
    	
    	注意:	服务器所返回的时间戳都是秒(JS是毫秒)
    **********************************************
    */
    
    //创建数据库之类的
    $db=@mysql_connect('localhost', 'root', '') or @mysql_connect('localhost', 'root', 'root');
    
    mysql_query("set names 'utf8'");
    mysql_query('CREATE DATABASE ajax');
    
    mysql_select_db('ajax');
    
    $sql= <<< END
    CREATE TABLE  `ajax`.`weibo` (
    `ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `content` TEXT NOT NULL ,
    `time` INT NOT NULL ,
    `acc` INT NOT NULL ,
    `ref` INT NOT NULL
    ) CHARACTER SET utf8 COLLATE utf8_general_ci
    END;
    
    mysql_query($sql);
    
    //正式开始
    
    //header('Content-type:xmg/json');
    
    $act=$_GET['act'];
    $PAGE_SIZE=6;
    
    switch($act)
    {
    	case 'add':
    		$content=urldecode($_GET['content']);
    		$time=time();
    		
    		$content=str_replace("
    ", "", $content);
    		
    		$sql="INSERT INTO weibo (ID, content, time, acc, ref) VALUES(0, '{$content}', {$time}, 0, 0)";
    		
    		mysql_query($sql);
    		
    		$res=mysql_query('SELECT LAST_INSERT_ID()');
    		
    		$row=mysql_fetch_array($res);
    		
    		$id=(int)$row[0];
    		
    		echo "{"error": 0, "id": {$id}, "time": {$time}}";
    		break;
    	case 'get_page_count':
    		$sql="select ceil(n) from (SELECT COUNT(*)/{$PAGE_SIZE} n FROM weibo) a";
    		
    		mysql_query($sql);
    		
    		$res=mysql_query($sql);
    		
    		//echo $res;
    		
    		$row=mysql_fetch_array($res);
    		
    		$count=(int)$row[0];
    		
    		echo "{"count": {$count}}";
    		break;
    	case 'get':
    		$page=(int)$_GET['page'];
    		if($page<1)$page=1;
    		
    		$s=($page-1)*$PAGE_SIZE;
    		
    		$sql="SELECT ID, content, time, acc, ref FROM weibo ORDER BY time DESC LIMIT {$s}, {$PAGE_SIZE}";
    		
    		$res=mysql_query($sql);
    		
    		$aResult=array();
    		while($row=mysql_fetch_array($res))
    		{
    			$arr=array();
    			array_push($arr, '"id":'.$row[0]);
    			array_push($arr, '"content":"'.$row[1].'"');
    			array_push($arr, '"time":'.$row[2]);
    			array_push($arr, '"acc":'.$row[3]);
    			array_push($arr, '"ref":'.$row[4]);
    			
    			array_push($aResult, implode(',', $arr));
    		}
    		if(count($aResult)>0)
    		{
    			echo '[{'.implode('},{', $aResult).'}]';
    		}
    		else
    		{
    			echo '[]';
    		}
    		break;
    	case 'acc':
    		$id=(int)$_GET['id'];
    		
    		$res=mysql_query("SELECT acc FROM weibo WHERE ID={$id}");
    		
    		$row=mysql_fetch_array($res);
    		
    		$old=(int)$row[0]+1;
    		
    		$sql="UPDATE weibo SET acc={$old} WHERE ID={$id}";
    		
    		mysql_query($sql);
    		
    		echo '{"error":0}';
    		break;
    	case 'ref':
    		$id=(int)$_GET['id'];
    		
    		$res=mysql_query("SELECT ref FROM weibo WHERE ID={$id}");
    		
    		$row=mysql_fetch_array($res);
    		
    		$old=(int)$row[0]+1;
    		
    		$sql="UPDATE weibo SET ref={$old} WHERE ID={$id}";
    		
    		mysql_query($sql);
    		
    		echo '{"error":0}';
    		break;
    	case 'del':
    		$id=(int)$_GET['id'];
    		$sql="DELETE FROM weibo WHERE ID={$id}";
    		//echo $sql;exit;
    		mysql_query($sql);
    		echo '{"error":0}';
    		break;
    }
    ?>
    
  • 相关阅读:
    数据库(MySQL):事务
    数据库(MySQL):存储引擎
    操作系统:虚拟存储器
    操作系统:内存管理
    操作系统:进程与线程
    近期目标
    计算机网络:TCP三次握手、四次挥手
    计算机网络:OSI与TCP/IP各层的结构与功能,都有哪些协议
    计算机网络:从输入URL到页面加载
    Java:JVM
  • 原文地址:https://www.cnblogs.com/zhongchao666/p/9462996.html
Copyright © 2020-2023  润新知