瑞星 发表于 2024-8-1 12:25:10

WEB前端13-Vue2常用指令

Vue2常用指令

1. 文本插值

Vue 中使用双大括号 {{ }} 进行文本插值,将数据渲染到 DOM 中:
<template>
    <div>
      <h1>{{ name }}</h1>
      <h1>{{ age > 60 ? '老年' : '青年' }}</h1>
    </div>
</template>
<script>
const options = {
    data: function () {
      return {
            name: '张三',
            age: 20
      };
    }
};
export default options;
</script>
注意事项和细节:


[*] 文本插值支持简朴的 JavaScript 表达式,但不保举在插值中使用复杂逻辑或方法调用。
[*] Vue 实例的 data 对象中定义的属性会相应式地更新视图,即当 message 改变时,相干的 DOM 会主动更新,默认为双向绑定。
[*] {{}} 里只能绑定一个属性,绑定多个属性需要用多个 {{}} 分别绑定
[*] Vue中还设置了v-text和v-html标签用于替换文档的内容,它与Js中的textContent和innerHTML属性的作用相同
2. 属性绑定

可以使用 v-bind 指令来动态绑定 HTML 属性:
<template>
<div>
    <img v-bind:src="imageURL">
</div>
</template>

<script>
export default {
data() {
    return {
      imageURL: 'https://example.com/image.jpg'
    };
}
};
</script>
注意事项和细节:


[*]v-bind 可以简写为 :,例如 :src="imageURL"。
[*]动态绑定的属性可以是 HTML 元素的任何属性,比如 href、class 等。
3. 事件绑定

使用 v-on 指令来监听 DOM 事件:
<template>
<div>
    <button @click="sayHello">Say Hello</button>
</div>
</template>

<script>
export default {
methods: {
    sayHello() {
      alert('Hello!');
    }
}
};
</script>
注意事项和细节:


[*]v-on 可以简写为 @,例如 @click="sayHello"。
[*]在 methods 中定义的方法可以在模板中通过 v-on 绑定到事件上,如许可以实现用户交互。
[*]在 methods 方法中的 this 代表的是 data 函数返回的数据对象
4. 双向绑定

使用 v-model 指令实现表单位素的双向绑定:
<template>
<div>
    <input v-model="message" type="text">
    <p>{{ message }}</p>
</div>
</template>

<script>
export default {
data() {
    return {
      message: '你好'
    };
}
};
</script>
注意事项和细节:


[*]v-model 只实用于表单位素,如 input、textarea 和 select。
[*]双向绑定会将输入框的值与 Vue 实例的数据属性同步,从而实现数据的双向活动。
[*]复选框这种标签,双向绑定的 javascript 数据类型一般用数组
5. 盘算属性

通过 computed 属性定义盘算属性,根据依赖进行缓存,只有在相干依赖发生厘革时才会重新盘算:
<!-- 计算属性 -->
<template>
        <div>
      显示全名:{{ fullName() }}<br />
      显示全名:{{ fullName1 }}<br />
    </div>
</template>

<script>
const options = {
    data: function () {
      return { xing: '李', ming: '四' };
    },
    methods: {
      fullName() {
      return this.xing + this.ming;}
    },

    computed: {
      fullName1() {
      return this.xing + this.ming;}
    },
};
export default options;
</script>
注意事项和细节:


[*]普通方法调用必须加 (),没有缓存功能
[*]盘算属性使用时就把它当属性来用,不加 (),有缓存功能:一次盘算后,会将效果缓存,下次再盘算时,只要数据没有厘革,不会重新盘算,直接返回缓存效果
6.条件渲染

v-if 和 v-else
v-if 是Vue.js中用来根据表达式的真假条件渲染元素的指令。它的基本用法如下:
<div v-if="condition">
<!-- 当条件为真时显示的内容 -->
</div>
此中,condition 是一个返回布尔值的表达式。如果 condition 为真,<div> 元素及其内容会被渲染到页面上;如果 condition 为假,则 <div> 元素不会被渲染。
有时候,我们需要在条件为假的情况下显示备选内容,这时可以使用 v-else:
<div v-if="condition">
<!-- 当条件为真时显示的内容 -->
</div>
<div v-else><!-- 当条件为假时显示的内容 --></div> v-else 指令必须紧跟在带有 v-if 的元素大概 v-if / v-else-if 块的后面,并且在同一父元素下。它表现,如果前面的 v-if 表达式为假,则渲染 v-else 后面的内容。


[*]注意:v-if现实就是根据表达式的布尔值对dom树中的节点进行增删,类似的v-show下令是通过display属性,根据表达式的布尔值动态展示
7.列表渲染

v-for 是Vue.js中用来渲染列表数据的指令,它能够根据数据源迭代渲染出多个元素。基本的用法如下:
<div v-for="item in items" :key="item.id">
{{ item.name }}
</div>
在这个例子中,items 是一个包罗多个对象的数组,每个对象都至少有一个唯一的 id 属性。v-for 指令会遍历 items 数组,为每个数组元素创建一个 <div> 元素,并显示 item.name 的内容。
注意事项:


[*]v-for 指令后面需要使用 in 关键字来指定遍历的源数据大概使用关键字of
[*]必须为每个迭代的元素提供一个唯一的 key 属性,以便于Vue.js识别每个节点的身份,优化渲染性能。
案例:动态表格

后端:
package com.tyut.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tyut.entity.Student;
import com.tyut.service.StudentService;

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.PrintWriter;
import java.util.List;

@WebServlet("/getStudentsServlet")
public class GetStudentsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      response.setContentType("text/html;charset=utf-8");
      response.addHeader("Access-Control-Allow-Origin", "http://localhost:7070");
      request.setCharacterEncoding("utf-8");

      PrintWriter out = response.getWriter();


      StudentService studentService = new StudentService();
      List<Student> allStudent = studentService.getAllStudent();

      // 创建 ObjectMapper 对象
      ObjectMapper objectMapper = new ObjectMapper();

      // 将集合转换为 JSON 字符串
      String jsonString = objectMapper.writeValueAsString(allStudent);

      out.write(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      this.doGet(request, response);
    }
}
前端:
<template>
<div>
    <div>
      <table>
      <caption>
          学生信息表
      </caption>
      <thead>
          <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>性别</th>
          </tr>
      </thead>
      <tbody v-if="students.length > 0">
          <tr v-for="s in students" :key="s.id">
            <td>{{ s.id }}</td>
            <td>{{ s.name }}</td>
            <td>{{ s.sex }}</td>
          </tr>
      </tbody>
      <tbody v-else>
          <tr>
            <td colspan="3" class="message">暂无学生数据</td>
          </tr>
      </tbody>
      </table>
    </div>

    <div v-text="students"></div>
    <div>{{ students }}</div>
</div>
</template>

<script>
import axios from "axios";

export default {
data() {
    return {
      students: [],
    };
},
mounted() {
    this.getStudents();
},
methods: {
    async getStudents() {
      try {
      const response = await axios.post("/management_system/getStudentsServlet");
      this.students = response.data;
      } catch (error) {
      console.error("Error fetching students:", error);
      }
    },
},
};
</script>

<style scoped>
caption {
text-align: center;
font-family: "腾讯体";
font-size: 50px;
}

table {
border: 2px solid silver;
margin: 0 auto; /* 设置左右外边距为自动,实现居中 */
width: 50%; /* 可根据需要调整宽度 */
border-spacing: 0;
}

th,
td {
border: 1px solid silver;
width: 100px;
height: 50px;
font-family: "黑体";
font-size: 25px;
text-align: center;
}

.message {
text-align: center;
}
</style>


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: WEB前端13-Vue2常用指令