Vue基础三

/ vue / 2 条评论 / 1269浏览

ajax

一般说来 Vue 不会直接使用原生的 Ajax 而是使用 ajax 框架。 而 fetch.js 就是眼下比较流行的一种 ajax 框架

fetch

fetch就是ajax的一种框架

<script src="https://cdn.bootcss.com/fetch/2.0.4/fetch.js"></script>

<div id="hello">
</div>

<script>
    var url = "http://****/json";
    fetch(url).then(function(response) {
        response.json().then(function (jsonObject) {
            var jsonStr = JSON.stringify(jsonObject);
            document.getElementById("hello").innerHTML= "fetch获取到的数据:"+jsonStr;
        })
    }).catch(function(err){
        console.log("错误:"+err);
    })
</script>

axios

axios就是ajax的一种框架

<script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>

<div id="hello">
    
</div>

<script>
    var url = "../json/json.txt";
    axios.get(url).then(function(response){
        var jsonObject = response.data;
        var jsonStr = JSON.stringify(jsonObject);
        document.getElementById("hello").innerHTML="axios获取到的json数据为:"+jsonStr;
    })
</script>

vue中使用ajax

推荐使用4、5方式

1. 原生 ajax
2. JQuery
3. vue-resource
4. fetch.js
5. axios.js

fetch.js 方式

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

<div id="div1">
    <table border="1px" align="center">
        <th>name</th>
        <th>hp</th>
        <tr>
            <td>{{lpl.name}}</td>
            <td>{{lpl.hp}}</td>
        </tr>
    </table>
</div>

<script>
    var url = "../json/json.txt";
    new Vue({
        el:'#div1',
        data:{
            lpl:[]
        },
        mounted:function(){ //mounted 表示这个 Vue 对象加载成功了
            self=this
            fetch(url).then(function(response) {
                response.json().then(function (jsonObject) {
                    self.lpl = jsonObject
                    //或者:vue.lpl= response.data;
                })
            }).catch(function(err){
                console.log("Fetch错误:"+err);
            })
        }
    })
</script>

axios.js 方式

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

<div id="div1">
    <table border="1px" align="center">
        <th>name</th>
        <th>hp</th>
        <tr>
            <td>{{lpl.name}}</td>
            <td>{{lpl.hp}}</td>
        </tr>
    </table>
</div>

<script>
    var url = "../json/json.txt";
    new Vue({
        el:'#div1',
        data:{
            lpl:[]
        },
        mounted:function(){ //mounted 表示这个 Vue 对象加载成功了
            self=this
            axios.get(url).then(function(response) {
                self.lpl= response.data; //此时还是字符串
                //或者:vue.lpl= response.data;
                self.lpl = eval("("+self.lpl+")");  //字符串转换为数组对象
            }) 
            //带参数
            var url =  this.uri+"?keyword="+keyword;
            axios.post(url).then(function(response) {
                  vue.products = response.data;
                  vue.$nextTick(function(){
                      linkDefaultActions();
                   })
            });
        }
    })
</script>

vue实现crud(静态)

列表显示

<!-- 
    1.引入需要的cdn
    2.准备数据
    3.构建vue对象
    4.页面上显示
 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>

<div id="app">
    <table border="1px" align="center">
        <th>战队</th>
        <th>人气值</th>
        <th>操作</th>
        <tr v-for="hero in data.heros">
            <td>{{hero.name}}</td>
            <td>{{hero.hp}}</td>
            <td>
                <a href="javascript:;">编辑</a>
                <a href="javascript:;">删除</a>
            </td>
        </tr>
    </table>
</div>

<script>
    //1.准备数据对象
     var data = {
            heros: [
            { id: 1, name: 'ig', hp: 318},
            { id: 2, name: 'fpx', hp: 320},
            { id: 3, name: 'rng', hp: 419},
            { id: 4, name: 'edg', hp: 325},
            { id: 5, name: 'tes', hp: 422},
            ],
            hero4Add: { id: 0, name: '', hp: '0'},
            hero4Update: { id: 0, name: '', hp: '0'}
        };
        
    //2.构建vue对象
    var vm = new Vue({
        el: '#app',
        data: {
            data: data
        }
    })
</script>

增加数据

<!-- 
    1.引入需要的cdn
    2.准备input标签 并用v-model绑定vue中的数据
    3.增加v-on:click事件
    4.vue书写add方法
 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>

<div id="app">
    <div align="center">
        战队:<input name="name" v-model="hero4Add.name"/>
        人气值:<input name="hp" v-model="hero4Add.hp"/> 
        <input type="button" value="增加" v-on:click="add"/>
    </div>
    <hr>
    <table border="1px" align="center">
        <th>id</th>
        <th>战队</th>
        <th>人气值</th>
        <th>操作</th>
        <tr v-for="hero in data.heros">
            <td>{{hero.id}}</td>
            <td>{{hero.name}}</td>
            <td>{{hero.hp}}</td>
            <td>
                <a href="javascript:;">编辑</a>
                <a href="javascript:;">删除</a>
            </td>
        </tr>
    </table>
</div>

<script>
    //1.准备数据对象
     var data = {
            heros: [
            { id: 1, name: 'ig', hp: 318},
            { id: 2, name: 'fpx', hp: 320},
            { id: 3, name: 'rng', hp: 419},
            { id: 4, name: 'edg', hp: 325},
            { id: 5, name: 'tes', hp: 422},
            ]
        };
        
    //2.构建vue对象
    var vm = new Vue({
        el: '#app',
        data: {
            data: data,
            hero4Add: { id: 0, name: '', hp: '0'},
            hero4Update: { id: 0, name: '', hp: '0'}
        },
        methods: {
            add: function(){
                //id为随机数
                this.hero4Add.id = Math.ceil(Math.random()*1000);
                //把对象加入到数组
                this.data.heros.push(this.hero4Add);
                //让 hero4Add 指向新的对象
                this.hero4Add = { id: 0, name: '', hp: '0'};
            }
        }
    })
</script>

删除数据

<!-- 
    1.给删除按钮绑定事件,并传递参数
    2.书写删除事件
 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>

<div id="app">
    <div align="center">
        战队:<input name="name" v-model="hero4Add.name"/>
        人气值:<input name="hp" v-model="hero4Add.hp"/> 
        <input type="button" value="增加" v-on:click="add"/>
    </div>
    <hr>
    <table border="1px" align="center">
        <th>id</th>
        <th>战队</th>
        <th>人气值</th>
        <th>操作</th>
        <tr v-for="hero in data.heros">
            <td>{{hero.id}}</td>
            <td>{{hero.name}}</td>
            <td>{{hero.hp}}</td>
            <td>
                <a href="javascript:;" >编辑</a>
                <a href="javascript:;" @click="del(hero.id)">删除</a>
            </td>
        </tr>
    </table>
</div>

<script>
    //1.准备数据对象
     var data = {
            heros: [
            { id: 1, name: 'ig', hp: 318},
            { id: 2, name: 'fpx', hp: 320},
            { id: 3, name: 'rng', hp: 419},
            { id: 4, name: 'edg', hp: 325},
            { id: 5, name: 'tes', hp: 422},
            ]
        };
        
    //2.构建vue对象
    var vm = new Vue({
        el: '#app',
        data: {
            data: data,
            hero4Add: { id: 0, name: '', hp: '0'},
            hero4Update: { id: 0, name: '', hp: '0'}
        },
        methods: {
            add: function(){
                //id为随机数
                this.hero4Add.id = Math.ceil(Math.random()*1000);
                //把对象加入到数组
                this.data.heros.push(this.hero4Add);
                //让 hero4Add 指向新的对象
                this.hero4Add = { id: 0, name: '', hp: '0'};
            },
            del: function(id){
                for(var i=0; i<this.data.heros.length; i++){
                    if(this.data.heros[i].id == id){
                        this.data.heros.splice(i, 1);
                        break;
                    }
                }
            }
        }
    })
</script>

axios表单数据提交&文件上传

数据和图片一起提交

前端准备

1.input标签准备,与getFile事件绑定 2.校验name和image不为空 3.axios 需要用如代码所示的 formData的形式来做,否则没法上传 4.调用 axios 的post方法进行实际的上传工作。

$(function () {
    //构建vue
    var vue = new Vue({
        el: '#workingArea',
        data: {
            uri: 'categories',
            beans: [],
            bean: {id: 0, name: ""},
            file: null
        },
        mounted: function () {//mounted标识此vue对象加载成功
            this.list(0);
        },
        methods: {
            getFile: function (event) {
                this.file = event.target.files[0];
            },
            add: function () {
                if(!checkEmpty(this.bean.name, '分类名称')){
                    return ;
                }
                if(!checkEmpty(this.file, '分类图片')){
                    return ;
                }
                var url = this.uri;
                //axios方式上传文件:formData
                var formData = new FormData();
                formData.append("image", this.file);
                formData.append("name", this.bean.name);
                //开始上传
                axios.post(url, formData).then(function (reponse) {
                    vue.list(0);//重置首页数据
                    vue.file = null;
                    vue.bean = {id: 0, name: ""};
                    $("#categoryPic").val();
                });
            }
        }
    })
})


<table class="addTable">
    <tr>
        <td>分类名称</td>
        <td><input  @keyup.enter="add" v-model.trim="bean.name" type="text" class="form-control"></td>
    </tr>
    <tr>
        <td>分类图片</td>
        <td>
            <input id="categoryPic" accept="image/*" type="file" name="image" @change="getFile($event)" />
        </td>
    </tr>
    <tr class="submitTR">
        <td colspan="2" align="center">
            <a href="#nowhere"  @click="add" class="btn btn-success">提交</a>
        </td>
    </tr>
</table>

后台处理

@RequestMapping(value = "/categories")
public Object add(Category category, MultipartFile image, HttpServletRequest request) throws IOException {
    Category bnea = categoryService.add(category);
    saveOrUpdateImageFile(bnea, image, request);//保存文件操作
    return category;
}

public void saveOrUpdateImageFile(Category bean, MultipartFile image, HttpServletRequest request)throws IOException{
    File imageFolder = new File(request.getServletContext().getRealPath("img/category"));
    File file = new File(imageFolder, bean.getId() + ".jpg");
    if(!file.getParentFile().exists()){
        file.getParentFile().mkdir();
    }
    //transferTo:文件保存.jpg后缀名
    image.transferTo(file);
    //change2jpg:格式化成jpg文件
    BufferedImage img = ImageUtil.change2jpg(file);
    //写入磁盘
    ImageIO.write(img, "jpg", file);
}