安装

需要在导入vue之后再引用,因为vue-resource需要依赖vue。
vue向document中挂载了一个vue对象,而vue-resource则在vue中挂载了$http.

调用方法

<script type="text/javascript" src = "./vue.js"></script>
<script type="text/javascript" src = "./vue-resource.js"></script>
<body>
	<div class = "app">

		<input type="button" value="getInfo" @click="getInfo" name="">
		<input type="button" value="postInfo" @click="postInfo" name="">
		<input type="button" value="jsonpInfo" @click="jsonpInfo" name="">
	</div>
</body>
<script type="text/javascript">
	var vm = new Vue({
		el:'.app',
		data:{

		},
		methods:{
			getInfo(){//发起get请求
				//通过then设置成功的回调函数
				this.$http.get('http://127.0.0.1:3000').then(function(res){
					//通过res.body获取服务器返回的数据
					console.log(res.body);
				})
			},
			postInfo(){
				//只接受表单格式数据 application/x-www-form-urlencoded
				//手动发起的post请求默认没有表单格式,部分服务器无法处理
				//通过post的方法的参数设置提交的类型为普通表单数据格式emulateJSON:true
				this.$http.post('http://127.0.0.1:3000/post',{},{emulateJSON:true}).then(function(res){
					console.log(res.body);
				})
			},
			jsonpInfo(){
				this.$http.jsonp('http://127.0.0.1:3000/jsonp').then(function(res){
					console.log(res.body);
				})
			}
		}
	})
</script>

jsonp:由于浏览器安全限制,不允许ajax访问;可通过动态创建script标签的形式,把script标签的src属性,只想数据接口的地址,因为script不存在跨域限制,这种数据获取方式称为jsonp(jsonp只支持get请求)
过程

  1. 现在客户端定义一个回调方法,预定义对数据操作;
  2. 再把这个回调方法的名称,通过url传参的形式,提交到服务器的数据接口;
  3. 服务器数据接口组织好要发送给客户端的数据,再拿着客户端传递过来的回调方法名称,拼接出一个调用这个方法的字符串,发送给客户端去解析执行;
  4. 客户端拿到服务器返回的字符串之后,当作script脚本去解析执行,这样就能拿到jsonp的数据了。

callback回调函数地址的获取可使用url.parse(req.url)

vue2 配置resolve_vue2 配置resolve

服务端

服务器代码使用nodejs

//引入模块
var express=require('express');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//创建服务器
var app=express();

//开启服务器并监听端口
app.listen(3000,function(){
    console.log('this express server is running at http://127.0.0.1:3000 ');

})

//注册app中间件use,可处理get和post请求
//app.use(function(req,res){
//    console.log('...')
//})
//跨域问题
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});


//注册get请求中间键
app.get('/',function(req,res){
    //服务器回应数据
    res.send('这是主页面的内容')
    //res.json(内容); //返回json内容
   // var 变量=req.query.键名;   //get请求传入的查询参数中对应键的值
})

app.post('/post',function(req,res){
    var result = {name:"link"}
    res.send(result);
})
//jsonp格式请求
const url = require('url');
app.get('/jsonp',function(req,res){
    const {pathname:url1,query} = url.parse(req.url,true);
    var urlObj = url.parse(req.url);

    var resultData = {
        text:"dia",
        id:"cow"
    }
    var result = `${query.callback}(${JSON.stringify(resultData)})`;
    res.send(result);
})

app.post('/submit',urlencodedParser,function(req,res){
    res.send('这是一个post请求的数据');
    var 变量=req.body.键名;  //post请求传入的查询参数中对应键的值
    //使用前先加载 require(‘body-parser‘);中间件
})

vscode启动服务,避免安装node,直接使用node.exe,配置如下:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "args": ["--experimental-worker","node服务.js"],
            "skipFiles": [
                "<node_internals>/**"
            ],
            //"program": "${workspaceFolder}\\node服务.js"
            "runtimeExecutable": "${workspaceFolder}/node"
        }
    ]
}

服务器端需要文件如下:

vue2 配置resolve_vue_02

实例

插件安装(bootstrap 3 snippets)

sublime中可用的bootstrap控件:
使用快捷键shift+ctrl+p,出现一个弹出框,输入“install”,单击 “Package Control:install Package”,再弹出一个框,输入bs3,找到并单击“Bootstrap3 Snippets”。弹出的页面中有个链接,打开下载插件安装包(最后一行时地址):

Package Control Messages
========================

Bootstrap 3 Snippets
--------------------

  ============================================================
  Thank you for installing Bootstrap 3 Snippets
  ============================================================
  Follow me on Twitter: @JasonMortonNZ
  ------------------------------------------------------------

  Bootstrap 3 snippets is a selection of snippets
  that will greatly improve your workflow.

  This package is compatible with both Sublime
  Text versions 2 & 3.

  Documentation, examples & issue filing can be found here:
  https://github.com/JasonMortonNZ/bs3-sublime-plugin

sublime中选择Preferences\Browse Packages,会打开一个目录,将插件包解压到这里,重启sublime。
打开后输入bs3-table + tab键就会生成代码段。

客户端代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<script type="text/javascript" src = "./vue.js"></script>
<link rel="stylesheet" href="./bootstrap.css">
<script type="text/javascript" src = "./vue-resource.js"></script>
<body>
	
	<div class = "app">
		<div class="panel panel-primary">
		
			<div class="panel-heading">
				<h3 class="panel-title">添加品牌</h3>
			</div>
			<div class="panel-body form-inline">
				<label>
					name:<input type="text" name="" class="form-control" v-model="name" >
				</label>

				<input type="button" value="添加" class="btn btn-primary"name="" v-on:click="add">
			</div>
		</div>

		<table class="table table-bordered table-hover table-striped">
			<thead>
				<tr>
					<th>id</th>
					<th>name</th>
					<th>ctime</th>
					<th>operation</th>
	
				</tr>
			</thead>
			<tbody>
				<tr v-for="item in list" v-bind:key="item.id">
					<td>{{item.id}}</td>
					<td>{{item.name}}</td>
					<td>{{item.ctime}}</td>
					<td><a href="" @click.prevent="del(item.id)"> 删除</a></td>
				</tr>
			</tbody>
		</table>
	</div>
</body>
<script type="text/javascript">
	//设置全局根域名
	Vue.http.options.root = 'http://127.0.0.1:3000/';
	// 全局配置post请求为表单形式,全局启用emulateJSON选项
	Vue.http.options.emulateJSON = true;
	var vm = new Vue({
		el:'.app',
		data:{
			list:[
				{id:1,name:"奔驰",ctime:new Date()},
				{id:2,name:"宝马",ctime:new Date()}
			],
			id:"",
			name:"",
			searchWord:""
		},
		methods:{
			add(){
				this.$http.post('add',{name:this.name},{}).then(result=>{
				// this.$http.post('add',{name:this.name},{emulateJSON:true}).then(result=>{
				// this.$http.post('http://127.0.0.1:3000/add',{name:this.name},{emulateJSON:true}).then(result=>{
					var res =result.body;
					if(res.status ==0 ){
						this.getlist();
					}else{
						alert("添加数据失败");
					}
				})
			},
			getlist(){
				//注意此处的路径不需要加/,根路径中已经配置了路径
				this.$http.get('getList').then(result=>{
				// this.$http.get('http://127.0.0.1:3000/getList').then(result=>{
					var res =result.body;
					if(res.status ==0 ){
						this.list = res.message;
					}else{
						alert("获取数据失败");
					}
				})
			},
			del(delID){
				// this.$http.get('http://127.0.0.1:3000/del?' + delID).then(result=>{
				this.$http.get('del?' + delID).then(result=>{
					if(result.body.status == 0){
						this.getlist();
					}else{
						alert("错误");
					}
				})
			}
		},
		created(){
			this.getlist();
		}
	})
</script>
</html>

服务端:

//引入模块
var express=require('express');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//创建服务器
var app=express();

//开启服务器并监听端口
app.listen(3000,function(){
    console.log('this express server is running at http://127.0.0.1:3000 ');

})

//注册app中间件use,可处理get和post请求
//app.use(function(req,res){
//    console.log('...')
//})
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});


//注册get请求中间键
app.get('/',function(req,res){
    //服务器回应数据
    res.send('这是主页面的内容')
    //res.json(内容); //返回json内容
   // var 变量=req.query.键名;   //get请求传入的查询参数中对应键的值
})




var list = {
    name:"link",
    status:0,
    message:[
        {id:1,
        name:"奥迪",
        ctime:"2020-02-07T10:35:25.000Z"
    },{
        id:2,
        name:"奥拓",
        ctime:"2020-03-07T10:35:25.000Z"
    }
    ]
}

app.get('/getList',function(req,res){
    res.send(list);
})

var querystring = require('querystring');
app.post('/add',function(req,res){
    var body = "";
    req.on('data', function (chunk) {
        body += chunk;
    });
    req.on('end', function () {
        // 解析参数
        body = querystring.parse(body);
        var newThing = {
            id:list.message[list.message.length-1].id +1,
            name : body.name,
            ctime:new Date()
        };
        list.message.push(newThing);
        var result = {
            status:0,
            message:"success"
        }

        res.send(result);
        // 设置响应头部信息及编码
        // res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
        
        // if(body.name && body.url) { // 输出提交的数据
        //     res.write("网站名:" + body.name);
        //     res.write("<br>");
        //     res.write("网站 URL:" + body.url);
        // } else {  // 输出表单
        //     res.write(postHTML);
        // }
        // res.end();
    });
})

var url = require('url');
app.get('/del',function(req,res){
    var param = url.parse(req.url,true).query;
    var id = Number(Object.keys(param)[0]);
    var indexDel = -1;
    list.message.forEach((value,index)=>{
        if(value.id == id){
            indexDel = index;
        }
    });
    list.message.splice(indexDel,1);
    var result = {
        status:0,
        message:"success"
    }
    res.send(result);
})

效果:

增删改查的功能。

vue2 配置resolve_数据_03

文化建设


己亥岁二首

泽国江山入战图,生民何计乐樵苏 凭君莫话封侯事,一将功成万骨枯 传闻一战百神愁,两岸强兵过未休 谁道沧江总无事,近来长共血争流