首页 > 其他分享 >快速入门VUE

快速入门VUE

时间:2022-08-31 22:57:53浏览次数:83  
标签:function el VUE 入门 data app Vue new 快速

准备Vue.js环境

  1. Java语言的程序包:jar包
    JavaScript语言的程序包:外部js文件
    对于Java程序来说,框架=jar包+配置文件。对于Vue来说,导入Vue的外部js文件就能够使用Vue框架了。

  2. Vue框架的js文件获取
    官网提供的下载地址:https://cdn.jsdelivr.net/npm/vue/dist/vue.js

使用Vue框架

 <!-- 使用{{}}格式,指定要被渲染的数据 -->
      <div id="app">{{message}}</div>
  • Vue写法
// 1.创建一个JSON对象,作为new Vue时要使用的参数
var argumentJson = {
   
   // el用于指定Vue对象要关联的HTML元素。el就是element的缩写
   // 通过id属性值指定HTML元素时,语法格式是:#id
   "el":"#app",
   
   // data属性设置了Vue对象中保存的数据
   "data":{
      "message":"Hello Vue!"
   }
};

// 2.创建Vue对象,传入上面准备好的参数
var app = new Vue(argumentJson);

元素绑定

单向元素绑定

  1. html代码
<div id="app">
   <!-- v-bind:value表示将value属性交给Vue来进行管理,也就是绑定到Vue对象 -->
   <!-- vueValue是一个用来渲染属性值的表达式,相当于标签体中加{{}}的表达式 -->
   <input type="text" v-bind:value="vueValue1" />
   <!--v-bind:value 可以简写成:value-->
   <input type="text" :value="vueValue2" />
   
   <!-- 同样的表达式,在标签体内通过{{}}告诉Vue这里需要渲染; -->
   <!-- 在HTML标签的属性中,通过v-bind:属性名="表达式"的方式告诉Vue这里要渲染 -->
   <p>{{vueValue1}}</p>
   <p>{{vueValue2}}</p>
</div>
  1. Vue绑定
var app = new Vue({
   "el":"#app",
   "data":{
      "vueValue1":"坤坤",
      "vaeValue2":"ikun"
   }
});

双向元素绑定

  1. html代码
<div id="app">
   <!-- v-bind:属性名 效果是从Vue对象渲染到页面 -->
   <!-- v-model:属性名 效果不仅是从Vue对象渲染到页面,而且能够在页面上数据修改后反向修改Vue对象中的数据属性 -->
   <input type="text" v-model:value="vueValue" />
   <!--:value可以省略-->
   <input type="text" v-model="vueValue" />

   <p>{{vueValue}}</p>
</div>
  1. Vue代码
// 创建Vue对象,挂载#app这个div标签
var app = new Vue({
   "el":"#app",
   "data":{
      "vueValue":"ikun"
   }
});
  • 当我们在输入框输入时,vueValue的值也会根治输入框的值改变
  1. trim修饰符
    实际开发中,要考虑到用户在输入数据时,有可能会包含前后空格。而这些前后的空格对我们程序运行来说都是干扰因素,要去掉。在v-model后面加上.trim修饰符即可实现。
<input type="text" v-model.trim="vueValue" />

vue基本语法

条件渲染

  1. html代码
<div id="app">
   <h3>if</h3>
   <div v-if="flag" style="width: 20px; height: 20px; background-color: red;"></div>
   <div v-if="!flag" style="width: 20px; height: 20px; background-color: blue;"></div>
</div>

<div id="app2">
   <h3>if/else</h3>
   <!--if 和 else之间不能有其他标签-->
   <div v-if="flag" style="width: 20px; height: 20px; background-color: red;"></div>
   <div v-else="flag" style="width: 20px; height: 20px; background-color: blue;"></div>
</div>

<div id="app03">
   <h3>v-show</h3>
   <!--v-show 通过display来显示和不显示div -->
   <img v-show="flag" src="./images/mimi.jpg" />
</div>
  1. Vue代码
var app = new Vue({
         "el":"#app",
         "data":{
            "flag":"true"
         }
      });

var app2 =new Vue({
   "el":"#app2",
   data:{
      "flag":"true"
   }
});

列表渲染

  1. html代码
<div id="app01">
   <ul>
      <!-- 使用v-for语法遍历数组 -->
      <!-- v-for的值是语法格式是:引用数组元素的变量名 in Vue对象中的数组属性名 -->
      <!-- 在文本标签体中使用{{引用数组元素的变量名}}渲染每一个数组元素 -->
      <li v-for="User in UserList">{{User}}</li>
   </ul>
</div>

<div id="app2">
        <!--border="1" width="400" cellpadding="4"-->
        <table border="1" width="400" cellpadding="4">
            <tr>
                <th>编号</th>
                <th>名称</th>
                <th>爱好</th>
                <th>备注</th>
            </tr>
            <tr v-for="user in UserList">
                <th>{{user.pid}}</th>
                <th>{{user.pname}}</th>
                <th>{{user.hobby}}</th>
                <th>{{user.mark}}</th>
            </tr>
        </table>
    </div>
  1. Vue代码
var app01 = new Vue({
   "el":"#app01",
   "data":{
      "UserList": [
         "panther",
         "Gin",
         "Kunkun",
         "ikun",
         "ji"
      ]
   }
});
 // app2
 var app2 = new Vue({
                "el":"#app2",
                "data":{
                    UserList:[
                        { pid:"1",pname:"panther",hobby:"play",mark:"ok"},
                        { pid:"2",pname:"Gin",hobby:"play",mark:"ok"},
                        { pid:"3",pname:"kunkun",hobby:"rop",mark:"ok"},
                        { pid:"4",pname:"ikun",hobby:"ball",mark:"ok"},
                        { pid:"5",pname:"ji",hobby:"junp",mark:"ok"}
                    ]
                }

            });

事件驱动

  1. 函数绑定
    html代码
<div id="app">
   <p>{{message}}</p>
   
   <!-- v-on:事件类型="事件响应函数的函数名" -->
   <button v-on:click="reverseMessage">Click me,reverse message</button>
</div>

Vue代码

var app = new Vue({
   "el":"#app",
   "data":{
      "message":"Hello Vue!"           
   },
   "methods":{
      "reverseMessage":function(){
         this.message = this.message.split("").reverse().join("");
      }
   }
});
  • 获取鼠标移动的坐标信息
<div id="app">
   <div style="width: 200px;height: 200px; 
      background-color=red;" v-on:mousemove="recordPosition"></div>
   <p id="showPosition">{{position}}</p>
</div>
var app = new Vue({
   "el":"#app",
   "data":{
      "position":"暂时没有获取到鼠标的位置信息"
   },
   "methods":{
      "recordPosition":function(event){
         this.position = event.clientX + " " + event.clientY;
      }
   }
});

侦听属性

  1. html代码
 <div id="app">
        <p>姓:{{firstName}}</p>
        <p>名:{{lastName}}</p>
        <input type="text" v-model="firstName" />
        <input type="text" v-model="lastName" />
        <p>全名:{{fullName}}</p>
    </div>
  1. Vue代码
var app = new Vue({
                "el":"#app",
                "data":{
                    "firstName":"ikun",
                    "lastName":"kun",
                    "fullName":"kunkun"
                },
                "watch":{
                    // 监听firstName
                    "firstName":function (inputValue) {
                        this.fullName = inputValue + " " + this.lastName;
                    },
                    "lastName":function (inputValue) {
                        this.fullName = this.firstName + " "+inputValue;
                    }
                }

            });

Vue对象生命周期

<div id="app">
        <p id="content">{{message}}</p>
        <button v-on:click="changeValue">click me</button>
    </div>
 var app = new Vue({

                "el":"#app",
                "data":{
                    "message":"hello"
                },
                "methods":{
                    "changeValue":function () {
                        this.message = "new Hello!"
                    }
                },

                // 实例创建之前
                "beforeCreate":function () {
                    console.log("beforCreate:"+this.message);
                },
                // 实例创建完成
                "created":function () {
                    console.log("Create:"+this.message);
                },
                // 数据挂载前
                "beforeMount":function () {
                    console.log(document.getElementById("content").innerText);
                },
                // 数据挂载完成
                "mounted":function () {
                    console.log(document.getElementById("content").innerText);
                },
                // 数据跟新之前
                "beforeUpdate":function () {
                    console.log(document.getElementById("content").innerText);
                },
                // 数据跟新完成
                "updated":function () {
                    console.log(document.getElementById("content").innerText);
                }

            });

输出顺序:
** beforCreate:undefined**
** created:hello**
** beforeMount:{{message}}**
** Mounted:hello**
** beforeUpdate:Hello**
** updated:new Hello!**

axios快速入手

:::tip
axios响应对象结构
:::
| config | 调用axios(config对象)方法时传入的JSON对象 |
| data | 服务器端返回的响应体数据 |
| headers | 响应消息头 |
| request | 原生JavaScript执行Ajax操作时使用的XMLHttpRequest |
| status | 响应状态码 |
| status Text | 响应状态码的说文本 |

普通请求发送

  1. 前端代码
<div id="div01">
        uname : <input type="text" v-model:value="uname" /><br>
        p w d : <input type="text" v-model:value="pwd" /><br>
        <p>{{uname}}{{pwd}}</p>
        <input type="button" @click="axios01" value="click me"/>
</div>
var vue = new Vue({
    "el":"#app",
    "data":{
      "uname":"panther",
      "pwd":"123456"
    },
    "methods":{
        "commonParam":function () {
            axios({
                "method":"post",
                "url":"/demo/AjaxServlet?method=commonParam",
                "params":{
                    "userName":vue.uname,
                    "userPwd":vue.pwd
                }
            }).then(function (response) {
                console.log(response);
            }).catch(function (error) {
                console.log(error);
            });
        }
    }
});
  1. 后端代码
 @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");

        String uname = req.getParameter("uname");
        String pwd = req.getParameter("pwd");
        System.out.println(uname+" "+pwd);

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/htmp; charset=utf-8");
        PrintWriter print = resp.getWriter();
        print.write(uname+" "+pwd);
    }

JSON请求发送

  • 前端代码
<button @click="requestBodyJSON">请求体JSON</button>
"methods":{
    "requestBodyJSON":function () {
        axios({
            "method":"post",
            "url":"/demo/AjaxServlet?method=requestBodyJSON",
            "data":{
                "stuId": 139,
                "stuName": "Gin",
                "subjectList": [
                    {
                        "subjectName": "java",
                        "subjectScore": 98
                    },
                    {
                        "subjectName": "Cpp",
                        "subjectScore": 87
                    }
                ],
                "teacherMap": {
                    "one": {
                        "teacherName":"tom",
                        "tearcherAge":23
                    },
                    "two": {
                        "teacherName":"jerry",
                        "tearcherAge":31
                    },
                },
                "school": {
                    "schoolId": 23,
                    "schoolName": "panther"
                }
            }
        }).then(function (response) {
            console.log(response);
        }).catch(function (error) {
            console.log(error);
        });
    }
}
  • 后端代码
protected void requestBodyJSON(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // 1.由于请求体数据有可能很大,所以Servlet标准在设计API的时候要求我们通过输入流来读取
    BufferedReader reader = request.getReader();

    // 2.创建StringBuilder对象来累加存储从请求体中读取到的每一行
    StringBuilder builder = new StringBuilder();

    // 3.声明临时变量
    String bufferStr = null;

    // 4.循环读取
    while((bufferStr = reader.readLine()) != null) {
        builder.append(bufferStr);
    }

    // 5.关闭流
    reader.close();

    // 6.累加的结果就是整个请求体
    String requestBody = builder.toString();

    // 7.创建Gson对象用于解析JSON字符串
    Gson gson = new Gson();

    // 8.将JSON字符串还原为Java对象
    Student student = gson.fromJson(requestBody, Student.class);
    System.out.println("student = " + student);

    System.out.println("requestBody = " + requestBody);

    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().write("服务器端返回普通文本字符串作为响应");
}

标签:function,el,VUE,入门,data,app,Vue,new,快速
From: https://www.cnblogs.com/panther9985/p/16644820.html

相关文章