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. yuv rgb 互转 公式 及算法

    1 前言 自然界的颜色千变万化,为了给颜色一个量化的衡量标准,就需要建立色彩空间模型来描述各种各样的颜色,由于人对色彩的感知是一个复杂的生理和心理联合作用的过程,所以在不同的应用领域中为了更好更准确的 ...

  2. netty源码解析目录

    第一章 java nio三大组件与使用姿势 二.netty使用姿势 三.netty服务端启动源码 四.netty客户端启动源码 五.NioEventLoop与netty线程模型 六.ChannelPi ...

  3. 如何确定一台linux主机是Linux (i386/i686)还是Linux (x86_64)

    在下软件包的时候,往往会遇到一个选择: 假设自己的主机是Linux,那么Linux (i386/i686)和Linux (x86_64)究竟应该选哪一个呢? 针对当今的硬件而言,如果你主机的CPU是6 ...

  4. elementUI tree组件获取当前选择所有选中(check)和半选中(indeterminate)的节点

    网上查了半天,一大堆都说要改源码的,最后发现有方法不用改源码的 获取方法如下 this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHa ...

  5. DLLImport的用法C#

    它来调用WIN32的API或者调用一下C或C++编写的DLL.使用实例:将编译好的C++ DLL拷贝到BIN目录(DLLImport会从程序启动目录BIN开始查找相应名称的DLL,未找到则转至syst ...

  6. 安装rcssmin方法

    #安装rcssmin方法'''pip install wheelpip install rcssmin --install-option="--without-c-extensions&qu ...

  7. solr+zookeeper集群配置

    将solr配置文件交给zookeeper进行管理 ./zkcli.sh -zkhost node01:2181,node02:2181,node03:2181 -cmd upconfig -confd ...

  8. C#反射实现 C# 反射 判断类的延伸类型 使用代码生成工具Database2Sharp快速生成工作流模块控制器和视图代码 C# ADO.NET的SqlDataReader对象,判断是否包含指定字段 页面中添加锚点的几种方式 .net 简单实用Log4net(多个日志配置文件) C# 常用小点

    C#反射实现   一.反射概念: 1.概念: 反射,通俗的讲就是我们在只知道一个对象的内部而不了解内部结构的情况下,通过反射这个技术可以使我们明确这个对象的内部实现. 在.NET中,反射是重要的机制, ...

  9. python itertools 模块讲解

    1.介绍itertools 是python的迭代器模块,itertools提供的工具相当高效且节省内存. 使用这些工具,你将能够创建自己定制的迭代器用于高效率的循环. - 无限迭代器 itertool ...

  10. python中的__new__与__init__,新式类和经典类(2.x)

    在python2.x中,从object继承得来的类称为新式类(如class A(object))不从object继承得来的类称为经典类(如class A()) 新式类跟经典类的差别主要是以下几点: 1 ...