JavaWeb之ServIet中Vue的简单使用

一、什么是Vue:

     Vue.js 是一个用于构建用户界面的渐进式JavaScript框架。它设计得非常灵活,可以轻松地被集成到项目中,无论是在一个小型的交互特性还是在一个复杂的单页应用程序(SPA)中。Vue.js 的核心库只关注视图层,易于学习,并且与其他库或现有项目集成。同时,Vue 也完全能够支持单文件组件和Vue生态系统提供的一系列现代前端开发功能。

二、Vue的特点:

Vue 的主要特点包括:

  1. 响应式数据绑定:Vue.js 使用数据绑定来自动更新DOM,当数据变化时,视图也会相应地更新。

  2. 组件系统:Vue.js 允许开发者通过组件化的方式构建应用,每个组件管理自己的状态和逻辑。

  3. 指令系统:Vue 提供了一系列的指令(如 v-if, v-for, v-bind, v-on 等),使得DOM操作变得更加简单。

  4. 易用性:Vue 的API设计简洁直观,易于上手。

  5. 灵活性:Vue 可以被用在Web应用的任何部分,无论是一个简单的交互特性还是一个全功能的SPA。

  6. 生态系统:Vue 拥有一个丰富的生态系统,包括官方维护的路由器(Vue Router)、状态管理库(Vuex)、以及构建工具(Vue CLI)。

  7. 单文件组件:Vue 支持 .vue 文件,这种单文件组件格式使得组件的结构、样式和逻辑都集中在一个文件中。

  8. 虚拟DOM:Vue 使用虚拟DOM来提高性能和效率,通过计算最小的更新来减少实际的DOM操作。

  9. 服务器端渲染(SSR):Vue 支持服务器端渲染,这对于SEO和首屏加载性能非常有帮助。

  10. TypeScript 支持:Vue 支持 TypeScript,使得开发者可以使用类型系统来增强代码的健壮。

三、Vue的好处:

  1. 易于上手:Vue.js 的API设计简洁直观,对于新手来说学习曲线平缓,容易上手。

  2. 灵活性:Vue.js 可以被用于构建任何规模的应用,从小的交互特性到大型的单页应用。

  3. 组件化:Vue.js 的组件化特性使得代码更加模块化,易于维护和重用。

  4. 响应式数据绑定:Vue.js 的响应式系统可以自动将数据状态同步到视图,减少手动DOM操作的需要。

  5. 单文件组件:Vue.js 的单文件组件(.vue 文件)将模板、JavaScript 和 CSS 代码整合在一起,提高了开发效率。

  6. 现代工具链:Vue CLI 提供了一个强大的现代前端项目脚手架,支持快速搭建项目并配置构建工具。

  7. 丰富的生态系统:Vue.js 拥有一个活跃的社区和丰富的插件、工具库,如 Vuex 状态管理、Vue Router 路由等。

  8. 高性能:Vue.js 使用虚拟DOM来提高性能,通过计算最小的更新来减少实际的DOM操作,从而提高应用性能。

  9. 可扩展性:Vue.js 可以与其他库或现有项目集成,也可以作为大型应用的一部分。

  10. 开发者体验:Vue.js 提供了诸如热重载(Hot Module Replacement, HMR)、ESLint 集成等特性,提高了开发体验。

  11. 渐进式框架:Vue.js 是一个渐进式框架,开发者可以按需引入所需的功能,保持应用的轻量级。

  12. 官方支持:Vue.js 由一个活跃的团队维护,定期更新和修复bug,提供稳定的开发环境。

  13. 社区支持:Vue.js 拥有一个庞大的开发者社区,提供了大量的教程、文章和讨论,方便开发者学习和解决问题。

  14. 跨平台能力:通过使用像 Nativescript-Vue 或 Weex 这样的库,Vue.js 可以用于开发跨平台的移动应用。

  15. TypeScript 支持:Vue.js 支持 TypeScript,为需要类型检查的开发者提供了便利。

这些好处使得 Vue.js 成为许多前端开发者的首选框架之一,特别是在需要快速开发和迭代的项目中。

四、使用 Vue.js 构建应用时,安装:

1.独立版本:

我们可以在 Vue.js 的官网上直接下载 vue.min.js 并用 <script> 标签引入。

2.使用 CDN 方法

以下推荐国外比较稳定的两个 CDN,国内还没发现哪一家比较好,目前还是建议下载到本地。

建议下载至本地使用更方便

五、起步:

代码示例:

(el,data,  methods是固定的api,固定写法不能改变)

<div id="vue_det">

<h1>site : {{ site }}</h1>

<h1>url : {{ url }}</h1>

<h1>{{ details() }}</h1>

</div>

<script type="text/javascript">

var vm = new Vue({

el:  '#vue_det',

data: { site: "菜鸟教程", url: "www.runoob.com", alexa: "10000" },

methods: {

details: function() {

return this.site + " - hello,java!"; } } })

</script>

六、条件语句:

1.v-if:

v-if 指令将根据表达式 seen(此值可以自定义名称) 的值(true 或 false )来决定是否插入 此元素。

2.v-else-if:
<template v-if="condition1"> 
<!-- 当 condition1 为 true 时渲染 --> 
</template> <template v-else-if="condition2">
 <!-- 当 condition1 为 false 且 condition2 为 true 时渲染 --> </template> 
<template v-else-if="condition3"> 
<!-- 当 condition1 和 condition2 都为 false 且 condition3 为 true 时渲染 --> </template> 
<template v-else> <!-- 当以上所有条件都为 false 时渲染 --> </template>
3.v-show:

v-if 指令将根据表达式 seen(此值可以自定义名称) 的值(true 或 false )来决定是否插入此元素。

七、循环语句:

y值可以自定义

八、和前端相结合的一个增删查改的例子:

只取前端:

HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="vue.min.js"></script>
    <link rel="stylesheet" href="showStu.css">
   
</head>
<body>
    <div id="app">
        <!-- <span>{{name}}</span> -->
       <div class="crud">
        <div class="insert" v-show="show1">
            id  :<input type="text" v-model="date1.id"><br>
            姓名:<input type="text" v-model="date1.name"><br>
            性别:<input type="text" v-model="date1.sex"><br>
            年龄:<input type="text" v-model="date1.age"><br>
            电话:<input type="text" v-model="date1.tel"><br>
            成绩:<input type="text" v-model="date1.scores"><br>
            学校:<input type="text" v-model="date1.school"><br>
            <button @click="add()">提交</button>
        </div>
        <div class="update" v-show="show">
            id  :<input type="text" v-model="date1.id"><br>
            姓名:<input type="text" v-model="date1.name"><br>
            性别:<input type="text" v-model="date1.sex"><br>
            年龄:<input type="text" v-model="date1.age"><br>
            电话:<input type="text" v-model="date1.tel"><br>
            成绩:<input type="text" v-model="date1.scores"><br>
            学校:<input type="text" v-model="date1.school"><br>
            <button @click="updateOk()">更新</button>
        </div>
    </div>
        <div class="show">
        <table>
            <tr>
                <th>id</th>
                <th>姓名</th>
                <th>性别</th>
                <th>年龄</th>
                <th>电话</th>
                <th>成绩</th>
                <th>学校</th>
                <th>操作一</th>
                <th>操作二</th>
            </tr>
            <tr v-for="(value,index) in msg">
                <td>{{msg[index].id}}</td>
                <td>{{msg[index].name}}</td>
                <td>{{msg[index].sex}}</td>
                <td>{{msg[index].age}}</td>
                <td>{{msg[index].tel}}</td>
                <td>{{msg[index].scores}}</td>
                <td>{{msg[index].school}}</td>
                <td><a href="#" v-on:click="del(index)">删除</a></td>
                <td><a href="#" v-on:click="update(index)">更新</a></td>
            </tr>
        </table>
    </div>
    </div>
    <script src="showStu.js"></script>
</body>
</html>

CSS代码:

*{
    margin: 0;
    padding: 0;
}
#app {
    display: flex;
    justify-content: space-between; /* 确保两个主要部分分布在页面的两端 */
    align-items: flex-start;        /* 顶部对齐 */
    padding: 20px;
}

.show {
    width: 65%;  /* 展示部分占较大比例 */
    overflow-x: auto; /* 如果表格太宽,允许横向滚动 */
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    margin-right: 2%; /* 与表单部分留出一些间隔 */
}

.crud {
    width: 30%;  /* 表单部分占较小比例 */
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    background-color: white;
    border-radius: 8px;
    padding: 20px;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th, td {
    text-align: left;
    padding: 12px;
    border-bottom: 1px solid #ddd;
}

th {
    background-color:#357abD;
    color: white;
}

button {
    background-color: #4a90e2;
    color: white;
    border: none;
    border-radius: 5px;
    padding: 10px 20px;
    cursor: pointer;
    margin-top: 10px;
}

button:hover {
    background-color: #45a049;
}

input[type="text"] {
    width: 90%;
    padding: 8px;
    margin-top: 8px;
    margin-bottom: 16px;
    border: 1px solid #ccc;
    border-radius: 4px;
}
a {
    text-decoration: none;
    color:  #00796b;
    font-weight: bold;
    font-size: 15px;
}
a:hover {
    color: #357abD;
}

JS代码:

new Vue({
    el:"#app",
    data:{
        name:"java课程",
        msg:[
            {
                    "id": 1,
                    "name": "bb",
                    "sex": "男",
                    "age": 19,
                    "tel": 15292743385,
                    "scores": 88.3,
                    "school": "商洛学院"
                },
                {
                    "id": 2,
                    "name": "cc",
                    "sex": "女",
                    "age": 20,
                    "tel": 15292743385,
                    "scores": 90,
                    "school": "宝鸡文理"
                },
                {
                    "id": 3,
                    "name": "dd",
                    "sex": "男",
                    "age": 17,
                    "tel": 16292743385,
                    "scores": 80,
                    "school": "商洛文理"
                },
                {
                    "id": 4,
                    "name": "ee",
                    "sex": "女",
                    "age": 19,
                    "tel": 15392743385,
                    "scores": 78.3,
                    "school": "西安文理"
                }, {
                    "id": 5,
                    "name": "ff",
                    "sex": "男",
                    "age": 29,
                    "tel": 13292743385,
                    "scores": 68.3,
                    "school": "西安文理"
                }, {
                    "id": 6,
                    "name": "uu",
                    "sex": "男",
                    "age": 29,
                    "tel": 17292743385,
                    "scores": 88.8,
                    "school": "宝鸡文理1"
                }, {
                    "id": 7,
                    "name": "cc1",
                    "sex": "男",
                    "age": 19,
                    "tel": 19292743385,
                    "scores": 98.3,
                    "school": "宝鸡文理"
                }, {
                    "id": 8,
                    "name": "cc2",
                    "sex": "男",
                    "age": 19,
                    "tel": 28292743385,
                    "scores": 78.3,
                    "school": "宝鸡文理"
                }], 
         date1:{
            "id": "",
            "name": "",
            "sex": "",
            "age": "",
            "tel": "",
            "scores": "",
            "school": ""
                },
                show1:true,
                show:false,
                index1:""
        
    },
    methods:{
            del:function(index){
                if(confirm("确定删除吗?")){
                    this.msg.splice(index,1);
                }
            },
            update:function(index){
                this.show1=false;
                this.show=true;
                let dd={};
                dd={...this.msg[index]};
                this.date1=dd;
                this.index1=index;
            
            },
            updateOk:function(){
                this.msg[this.index1]=this.date1;
                this.show1=true;
                this.show=false;
                this.date1={};
            },
            add:function(){
                if(this.date1.name =="" || this.date1.sex =="" || this.date1.age =="" || this.date1.tel =="" 
                || this.date1.scores =="" || this.date1.school ==""){
                    alert("数据不完整")
                    return;
                }
                let ww={};
                ww ={...this.date1};
                this.msg.push(ww);
            this.date1.id='';
            this.date1.name="";
            this.date1.sex="";
            this.date1.age="";
            this.date1.tel="";
            this.date1.scores="";
            this.date1.school="";
            }
    }
})

九、和后端结合:Vue.js Ajax(axios)的相结合:

Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。

Github开源地址: GitHub - axios/axios: Promise based HTTP client for the browser and node.js

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

使用get方法:

(使用mybatis的注解方式和数据库连接:)

后端代码:


import Dao.StudentDao;
import Model.Students;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/ajax4")
public class ajax4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        InputStream on = Resources.getResourceAsStream("config/mybatis_config.xml");
        SqlSessionFactory build1 = new SqlSessionFactoryBuilder().build(on);
        SqlSession sqlSession1 = build1.openSession();
        StudentDao studentDao1 = sqlSession1.getMapper(StudentDao.class);
        List<Students> all = studentDao1.findAll1();
        req.setAttribute("all",all);
        String s = JSON.toJSONString(all);
        System.out.println("s = " + s);
        resp.setContentType("application/json");
        //       后端产生数据,返回前端
        req.setCharacterEncoding("utf-8");//响应用户请求,告知编码
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
       writer.write(s);
       //释放资源和对象
       writer.flush();
       writer.close();
    }
}

接口代码:

javaBean代码:

和数据库字段类型和名称相同

create和mounted的区别:

在 Vue.js 中,createdmounted 是 Vue 实例的生命周期钩子,它们在组件的不同阶段被调用,具有不同的作用:

  1. created

    • created 钩子在实例初始化之后被调用,此时组件的数据观测和事件/侦听器的配置已经完成。
    • 但是,组件尚未挂载到 DOM 上,所以在这个钩子中你不能访问 $el 属性,也不能执行依赖于 DOM 的操作。
    • 适合在这个钩子中执行数据的初始化操作,如调用异步请求来获取数据,或者设置初始状态。
  2. mounted

    • mounted 钩子在 el 选项存在的组件中被调用,即在组件被挂载到 DOM 之后。
    • 此时,你可以访问到 DOM 元素,并且可以执行依赖于 DOM 的操作,比如使用 this.$refs 访问子组件或 DOM 元素。
    • 适合在这个钩子中执行与 DOM 相关的初始化,比如执行 DOM 操作、第三方库的初始化等。

以下是它们在 Vue 组件中的使用示例:

export default {
  data() {
    return {
      message: 'Hello World'
    };
  },
  created() {
    // 组件实例已经创建,但是尚未挂载到 DOM
    console.log('Component is created');
    // 可以执行异步操作,如 API 请求
    this.fetchData();
  },
  mounted() {
    // 组件已经被挂载到 DOM
    console.log('Component is mounted');
    // 可以执行依赖于 DOM 的操作
    this.doSomethingWithDOM();
  },
  methods: {
    fetchData() {
      // 示例:获取数据
    },
    doSomethingWithDOM() {
      // 示例:DOM 操作
    }
  }
};

总结区别:

  • created:组件实例已创建,但尚未挂载到 DOM。
  • mounted:组件已经挂载到 DOM,可以执行依赖 DOM 的操作。

根据你的具体需求,选择合适的生命周期钩子来执行相应的初始化逻辑。

JS代码需要做出改变:

使用的get方法

new Vue({
    el:"#app",
    data(){
       //挂载后,使用return返回其值传递给下面
        return {
            name: "java课程",
            msg: null,
            date1: {
                "id": "",
                "name": "",
                "sex": "",
                "age": "",
                "tel": "",
                "scores": "",
                "school": ""
            },
            show1: true,
            show: false,
            index1: ""
        }
    },
    created(){
        axios
            .get('/webApp_war_exploded/ajax4')
            .then(response =>(this.msg = response.data))
            .catch(function (error){
                console.log(error);
            });
    },
    // mounted(){
    //
    // }
    methods:{
        del:function(index){
            if(confirm("确定删除吗?")){
                this.msg.splice(index,1);
            }
        },
        update:function(index){
            this.show1=false;
            this.show=true;
            let dd={};
            dd={...this.msg[index]};
            this.date1=dd;
            this.index1=index;

        },
        updateOk:function(){
            this.msg[this.index1]=this.date1;
            this.show1=true;
            this.show=false;
            this.date1={};
        },
        add:function(){
//这个是对表单空白值的一个判断,当错误的时候,不能成功添加
            // if(this.date1.name =="" || this.date1.sex =="" || this.date1.age =="" || this.date1.tel ==""
            //     || this.date1.scores =="" || this.date1.school ==""){
            //     alert("数据不完整")
            //     return;
            // }
            for (let i = 0; i <Object.keys(this.date1).length ; i++) {

                if (this.date1[Object.keys(this.date1)[i]]==""){
                    alert("值不完整!");
                    return;
                }
            }
            let ww={};
            ww ={...this.date1};
            this.msg.push(ww);
            this.date1.id='';
            this.date1.name="";
            this.date1.sex="";
            this.date1.age="";
            this.date1.tel="";
            this.date1.scores="";
            this.date1.school="";
        }
    }

  • 14
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值