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("\n", "", $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;
}
?>

11.vue 数据交互的更多相关文章

  1. Vue数据交互

    注意:本地json文件必须放在static目录下面,读取或交互数据前,请先安装vue-resource.点击前往  -->(vue-resource中文文档) 一.Vue读取本地JSON数据 c ...

  2. springMVC学习(11)-json数据交互和RESTful支持

    一.json数据交互: json数据格式在接口调用中.html页面中较常用,json格式比较简单,解析还比较方便. 比如:webservice接口,传输json数据. springMVC进行json交 ...

  3. webpack+vue项目实战(四,前端与后端的数据交互和前端展示数据)

    地址:https://segmentfault.com/a/1190000010063757 1.前言 今天要做的,就是在上一篇文章的基础上,进行功能页面的开发.简单点说呢,就是与后端的数据交互和怎么 ...

  4. vue前后台数据交互vue-resource文档

    地址:https://segmentfault.com/a/1190000007087934 Vue可以构建一个完全不依赖后端服务的应用,同时也可以与服务端进行数据交互来同步界面的动态更新. Vue通 ...

  5. vue中的数据监听以及数据交互

    现在我们来看一下vue中的数据监听事件$watch, js代码: new Vue({ el:"#div", data:{ arr:[,,] } }).$watch("ar ...

  6. 常用vue请求交互数据方式

    几种 vue的数据交互形式 var that=this get请求 that.$http.get("1.txt").then(function(result){ console.l ...

  7. Vue中独立组件之间数据交互

    独立组件之间数据交互:通过自定义事件 组件A中的[数据],传递给组件B 1.创建组件A,组件B 2.组件B在实例创建完成时就开始监听事件[等待接收数据]:钩子 3.组件A中触发事件,发送数据 注意:接 ...

  8. Vue框架(二)——Vue指令(v-once指令、v-cloak指令、条件指令、v-pre指令、循环指令)、todolist案例、Vue实例(计算、监听)、组件、组件数据交互

    Vue指令 1.v-once指令  单独使用,限制的标签内容一旦赋值,便不可被动更改(如果是输入框,可以主动修改) <!DOCTYPE html> <html lang=" ...

  9. vue,一路走来(3)--数据交互vue-resource

    所有的静态页面布局完成后,最重要的就是数据交互了,简单来说,vue-resource就像jquery里的$.ajax,用来和后台交互数据的.放在created或ready里运行来获取或者更新数据的.不 ...

随机推荐

  1. PL/SQL学习笔记之日期时间

    一:PL/SQL时间相关类型 PL/SQL提供两个和日期时间相关的数据类型: 日期时间(Datetime)数据类型 时间间隔类型 二:日期时间类型 datetime数据类型有: DATE TIMEST ...

  2. cmd命令行的ping用法

    1.打开cmd 2.ping 域名    (如:ping baidu.com) 3.输出结果 C:\WINDOWS\system32>ping baidu.com 正在 Ping baidu.c ...

  3. 美国FICO评分系统简介

    美国的个人信用评分系统,主要是Fair IsaacCompany 推出的 FICO,评分系统也由此得名.一般来讲, 美国人经常谈到的你的得分 ,通常指的是你目前的FICO分数.而实际上, Fair I ...

  4. centos 环境搭建jenkins服务

    1.下载jenkins war包 https://jenkins.io/download/ 选择Generic Java package (.war)下载2.下载apache tomcat 8 htt ...

  5. 为啥百度、网易、小米都用Python?Python的用途是什么?

      Python是一门脚本语言.由于能将其他各种编程语言写的模块粘接在一起,也被称作胶水语言.强大的包容性.强悍的功能和应用的广泛性使其受到越来越多的关注,想起一句老话:你若盛开.蝴蝶自来. 假设你感 ...

  6. C# 反射获取控件

    Control control = Controls.Find(]; //object o = control.GetType().GetProperty("PropertyName&quo ...

  7. Linux下源码安装xz的方法

    xz是一个不太常见但又效率非常高的解压缩软件,安装方法如下 ,cd /usr/local/src ,wget https://tukaani.org/xz/xz-5.2.3.tar.gz //下载到/ ...

  8. /linux-command-line-bash-shortcut-keys/

    https://www.howtogeek.com/howto/ubuntu/keyboard-shortcuts-for-bash-command-shell-for-ubuntu-debian-s ...

  9. 10款WordPress的插件让你的网站的移动体验

    随着科技的不断发展,需要改变营销策略的一个企业就变得非常重要.你不能指望用你的营销工具来留住你的客户.智能手机和平板电脑已经改变了消费者的行为方式.现在,人们甚至不想去他们的电脑或笔记本电脑,以检查产 ...

  10. Caffe 分类问题 Check failed: error == cudaSuccess (2 vs. 0) out of memory

    如果图片过大,需要适当缩小batch_size的值,否则使用GPU时可能超出其缓存大小而报错