一.Vue中的条件渲染

news/2025/2/26 2:11:10

1.在<head>中引用

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

2.在<body>中写入

<div id="app">
        <p>
            <a v-if ="user.username=='admin'"href="#">编辑</a>
            <a v-if="user.username!='guest'" href="#">详情</a>
        </p>
        <p>
            <a v-if ="user.username=='admin'"href="#">编辑</a>
            <a v-else href="#">详情</a>
        </p>
        <p>
            <a v-show ="user.username=='admin'"href="#">编辑</a>
            <a v-show="user.username!='admin'" href="#">详情</a>
        </p>
        <p>
            <button type="button" @click="change">切换成Guest</button>
        </p>
    </div>

3.在script中写入

<script>
        const {createApp} = Vue
        createApp({
            data(){
                return {
                    user:{
                        username:'admin'
                    }
                }
            },
            methods:{
                change:function(event){
                    if(this.user.username == 'admin'){
                        this.user.username = 'guest'
                        event.target.innerHTML = '切换成Admin'
                    }else{
                        this.user.username = 'admin'
                        event.target.innerHTML = '切换成Guest'
                    }
                }
            }        
        }).mount('#app')
 </script>

(1)v-if

  • 用途:根据表达式的真假值来条件性地渲染一个元素。
  • 行为:如果表达式的值为真,则渲染元素及其内容;如果为假,则不渲染。v-if 有“惰性”渲染的特性,即在条件首次评估为假时,元素及其绑定的数据都不会被创建或渲染;当条件变为真时,才会开始渲染。
  • 适用场景:适用于条件渲染,且条件在初始渲染时不太可能改变的情况,或者条件改变时涉及大量 DOM 操作的情况。

    (2)v-show

      用途:根据表达式的真假值来显示或隐藏一个元素。

    • 行为:无论表达式的值是真还是假,元素始终会被渲染并保留在 DOM 中。v-show 只是简单地切换元素的 CSS display 属性。
    • 适用场景:适用于需要频繁切换显示/隐藏状态,且切换代价较小的情况,因为元素始终保留在 DOM 中,只是简单地切换可见性。

     (3)v-for

    • 用途:基于源数据多次渲染元素或模板块。
    • 行为v-for 指令需要以特殊语法 item in items 的形式来使用,其中 items 是源数据数组或对象,item 是被迭代的数组元素或对象的值。v-for 还支持一个可选的第二个参数,即当前项的索引或键名。
    • 适用场景:适用于需要渲染列表或集合的情况,如用户列表、商品列表等

    二.列表渲染

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>列表渲染</title>
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </head>
    <body>
        <div id="app">
            <ul>
                <li v-for="(u,index) in users">
                   {{index}}_{{u.id}}_{{u.name}}_{{u.age}}
                </li>
            </ul>
        </div>
        <script>
            const {createApp} = Vue
            createApp({
                data(){
                    return {
                        users:[
                            {id:1,name:'zhangsan',age:18},
                            {id:2,name:'lisi',age:19},
                            {id:3,name:'wangwu',age:20},
                        ]
                    }
                },
                methods:{
                    
                }        
            }).mount('#app')
        </script>
    </body>
    </html>

    三.ref属性-此写法只适合Vue2

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>ref属性-此写法只适合Vue2</title>
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </head>
    <body>
        <div id="app">
            <p>
                <input type="text" value="admin" ref="username">
                <input type="button" value="获取用户名称" @click="getUsername">
            </p>
        </div>
        <script>
            
            const {createApp} = Vue
            
            createApp({
                data(){
                    return {
                                        
                            
                        
    
                    }
                        
                        
                        
                    },
                methods:{
                    getUsername(){
                        alert(this.$refs.username.value)
                    }
                }        
                
                
            }).mount('#app')
        </script>
    </body>
    </html>

    ref和refs的区别:

            

    1. ref

      • “ref”用于给元素或子组件注册引用信息。
      • 当“ref”应用于普通DOM元素时,引用指向的是该DOM元素;而当应用于子组件时,引用则指向组件实例。
      • 通过“ref”,开发者可以在父组件中方便地访问和操作这些被标记的元素或组件。
    2. refs

      • 在Vue.js等框架中,“$refs”是一个对象,用于存储所有通过“ref”属性注册的引用信息。
      • 可以通过“refs”轻松访问和操作这些被标记的元素或组件。例如,“this.refs.myElement”可以访问名为“myElement”的DOM元素或子组件实例。

    代码效果:

    四.计算属性

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>计算属性</title>
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </head>
    <body>
        <div id="app">
            姓:<input type="text" v-model="firstName1">
            名:<input type="text" v-model="lastName1">
            姓名:<input type="text" v-model="username1">
            <br><br>
            姓:<input type="text" v-model="firstName2">
            名:<input type="text" v-model="lastName2">
            姓名:<input type="text" v-model="username2">
        </div>
        <script>
            
            const {createApp} = Vue
            
            createApp({
                data(){
                    return {
                         firstName1:'',
                         lastName1:'',    
                         firstName2:'',
                         lastName2:''              
                    }        
                        
                },
                
                methods:{
                    
                },
                computed:{
                    //在computed属性对象中定义计算属性的方法,用于对数据进行计算操作
                    //通过getter和setter实现对属性数据的显示进行监控
                    username1:function(){
                        return this.firstName1+'' + this.lastName1
                    },
                    username2:{
                       get:function(){
                           return this.firstName2+''+ this.lastName2
                        },
                       set:function(val){
                           let strs=val.split(' ')
                           this.firstName2=strs[0]
                           this.lastName2=strs[1]
                        }
                    }        
                }    
                
            }).mount('#app')
        </script>
    </body>
    </html>

    代码效果:

    五.监听属性

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>监听属性</title>
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </head>
    <body>
        <div id="app">
            姓:<input type="text" v-model="firstName">
            名:<input type="text" v-model="lastName">
            姓名:<input type="text" v-model="username">
        </div>
        <script>
            const {createApp} = Vue
            createApp({
                data(){
                    return {
                        firstName:'',
                        lastName:'',
                        username:''           
                    }        
                        
                },
                watch:{
                    //通过Vue对象的$watch方法监听属性或watched的配置来监听指定属性
                    //当属性变化时,回调函数自动调用,在函数内部进行计算
                    username:function(newVal,oldVal){
                        if(newVal!=''){
                            let strs=newVal.split(' ')
                            this.firstName=strs[0]
                            this.lastName=strs[1]
                        }else{
                            this.firstName=''
                            this.lastName=''
                        }
                    },
                    firstName:function(){
                        this.username=this.firstName+' '+this.lastName
                    },
                    lastName:function(){
                        this.username=this.firstName+' '+this.lastName
                    }
                }
            }).mount("#app")
        </script>
    </body>
    </html>

    六.更新购买数量

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>更新购买数量</title>
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </head>
    <body>
        <div id="app">
            <button type="button" @click="sub">-</button>
            <input type="text" v-model="number" style="width: 50px; text-align: center;">
            <button type="button" @click="add">+</button>
        </div>
        <script>
            
            const {createApp} = Vue
            
            createApp({
                data(){
                    return {
                        number:1      
                    }        
                        
                },
                methods:{
                    add(){
                       if(this.number<10){
                           this.number++
                       } 
                    },
                    sub(){ 
                        if(this.number>1){
                            this.number--
                        }
                    }
                }
                
                
            }).mount('#app')
        </script>
    </body>
    </html>

    七.图片的切换

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>图片切换</title>
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
        <style>
            #box{
                width: 960px;
                height: 540px;
                margin:50px auto;
                border-top:10px solid #ccc;
                border-left:10px solid #ccc;
                border-right:10px solid #666;
                border-bottom:10px solid #666;
                padding:5px;
            }
            .btnLeft{
                width:100px;
                font-size:40px;
                color:#000;
                position: relative;
                top:-310px;
                left:0px;
                opacity:0.2;
                display:inline-block;
                cursor: pointer;
            }
            .btnRight{
                width:100px;
                font-size:40px;
                color:#000;
                position: relative;
                top:-310px;
                right:-820px;
                opacity:0.2;
                display:inline-block;
                cursor: pointer;
            }
            img{
                width:960px;
                height:540px;
            }
            
        </style>
    </head>
    <body>
        <div id="app">
            <div id="box">
                <img :src="images[currentIndex]">
                <div class="btnLeft" @click="left">《</div>
                <div class="btnRight" @click="right">》</div>
            </div>
        </div>
        <script>
            const {createApp} = Vue
            createApp({
                data(){
                    return {
                         images:[
                            'images/1.jpg',
                            'images/2.jpg',
                            'images/3.jpg',
                         ],
                         currentIndex:0  
                    }        
                        
                },
                methods:{
                    left(){
                        if(this.currentIndex>0)
                        {
                            this.currentIndex--;
                        }
                    },
                    right(){
                        if(this.currentIndex<this.images.length-1)
                        {
                            this.currentIndex++;
                        }
                    }
                    
                }
                
                
            }).mount('#app')
        </script>
    </body>
    </html>

    八.全选/全部选

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>全选/全不选</title>
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </head>
    <body>
        <div id="app">
            <p>
                <input type="checkbox" v-model="checkedAll" @click="choose">全选/全不选
            </p>
            <p>
                <span v-for="item in hobbys">
                    <input type="checkbox" v-model="ids" :value="item.id">{{item.title}}
    
                </span>
            </p>
        </div>
        <script>
            const {createApp} = Vue
            createApp({
                data(){
                    return {
                         hobbys:[
                            {id:1,title:'运动'},
                            {id:2,title:'音乐'},
                            {id:3,title:'美术'},
                            {id:4,title:'学习'},
                            
                         ],
                         ids:[
    
                         ],//爱好是否勾选
                         checkedAll:false //是否全选,默认false
                    }        
                        
                },
                methods:{
                    choose(){
                        if(this.checkedAll==true){
                            this.ids=[]
                            
                        }else{
                            this.hobbys.forEach(item=>{
                                this.ids.push(item.id)
                            })
                        }
                    }                
                },
                watch:{
                    ids:function(){
                        if(this.ids.length==this.hobbys.length){
                            this.checkedAll=true
                        }else{
                            this.checkedAll=false
                        }
                    }
                }
                
                
            }).mount('#app')
        </script>
    </body>
    </html>

    九.Vue综合案例

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        
        <style>
            * { margin: 0px; padding: 0px }
            h1 { text-align: center; width: 600px; margin: 100px auto 10px auto; }
            #box { width: 600px; margin: 0px auto; border: solid #ccc 1px; }
            #box input { width: 530px; border: 0px; padding: 10px 5px; font-size: 20px }
            #box ul { border-top: solid 1px #ccc;list-style: none;padding: 10px 5px; }
            #box ul li { font-size: 18px;line-height: 35px; }
            .left { float: left;color: #999;cursor: pointer }
            .right { float: right;color: #999;cursor: pointer }
            .clearfix:after, .clearfix:before { content: ""; display: table; clear: both; }
            .remove { color: #999;float: right;cursor: pointer;font-size: 20px; }
            #btn { width: 60px;height: 44px;border: 0px;cursor: pointer; }
        </style>
        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </head>
    <body>
        <div id="app">
            <h1>我的记事本</h1>
            <div id="box">
                <div>
                    <input type="text" v-model="record" placeholder="请填写您的记事信息">
                    <button id="btn" type="button" @click="save">添加</button>
                </div>
                <ul class="clearfix">
                    <li v-for="(item,index) in records" style="border-bottom: dotted 1px #ccc">
                        <span @click="modify(index)" style="cursor: pointer">{{index+1}}.{{item.content}}</span>
                        <span @click="remove(index)" class="remove" >&nbsp;x&nbsp;</span>
                    </li>
                    <li>
                        <span class="left">Total {{records.length}} Records</span>
                        <span class="right" @click="removeAll()">Remove All</span>
                    </li>
                </ul>
            </div>
        </div>
        <script>
            const {createApp} = Vue
            createApp({
                data: function () {
                    return {
                        records:[//记录记事本列表
                            {id:1,content:'今日记事,晚上跑步!'},
                            {id:1,content:'今日记事,晚上复习2小时!'},
                        ],
                        record:'',//记录事项
                        currentId:3,//当前事项最大id
                        motifyId:0//修改事项Id
                    }
                },
                methods:{
                    save(){//添加事项
                        if(this.record===''){
                            alert("请填写要记事的内容")
                        }else{
                            if(this.motifyId===0){//如果修改id等于0则表示添加新的记事内容
                                this.records.push({id:this.currentId,content:this.record})
                                this.currentId++
                            }else{
                                //修改事项
                                //循环获得记事本中每一个事项,寻找到要修改的事项并覆盖内容
                                for(let i=0;i<this.records.length;i++){
                                    if(this.records[i].id===this.motifyId){
                                        this.records[i].content=this.record
                                    }
                                }
                            }
                            this.record=''//清空输入框内容
                        }
    
                    },
                    modify(index){
                        let record=this.records[index]
                        this.record=record.content
                        this.motifyid=record.id
                    },
                    remove(index){
                        this.records.splice(index,1)//splice函数用于删除数组中的元素,参数1要删除元素的下标数,参数2删除几条数据
                    },
                    removeAll(){
                        this.records=[]//清空记录列表
                        this.modifyId=0//清空修改id
                        this.currentId=3//清空当前id
                    }
            
            }}).mount('#app')
        </script>
    </body>
    </html>


    http://www.niftyadmin.cn/n/5867073.html

    相关文章

    从单片机的启动说起一个单片机到点灯发生了什么下——使用GPIO点一个灯

    目录 前言 HAL库对GPIO的抽象 核心分析&#xff1a;HAL_GPIO_Init 前言 我们终于到达了熟悉的地方&#xff0c;对GPIO的初始化。经过漫长的铺垫&#xff0c;我们终于历经千辛万苦&#xff0c;来到了这里。关于GPIO的八种模式等更加详细的细节&#xff0c;由于只是点个灯&am…

    欢乐力扣:快乐数

    文章目录 1、题目描述2、思路1代码 1、题目描述 快乐数。  编写一个算法来判断一个数 n 是不是快乐数。  快乐数定义为&#xff1a;对于一个正整数&#xff0c;每次不断将其转化成 每位数字的平方和。 判断是否最终和会为1&#xff0c;是1就是快乐数&#xff0c;否则不是。 …

    【练习】【回溯:分割】力扣131. 分割回文串

    题目 分割回文串 给你一个字符串 s&#xff0c;请你将 s 分割成一些子串&#xff0c;使每个子串都是 回文串 。返回 s 所有可能的分割方案。 示例 1&#xff1a; 输入&#xff1a;s “aab” 输出&#xff1a;[[“a”,“a”,“b”],[“aa”,“b”]] 示例 2&#xff1a; 输入&am…

    关于Postman自动获取token

    在使用postman测试联调接口时&#xff0c;可能每个接口都需要使用此接口生成的令牌做Authorization的Bearer Token验证&#xff0c;最直接的办法可能会是一步一步的点击&#xff0c;如下图&#xff1a; 在Authorization中去选择Bearer Token&#xff0c;然后将获取到的token粘贴…

    编写最简单flink应用并提交到flink v1.19.2集群

    1 概述 本文介绍编写最最简单的word count的代码&#xff0c;编译成jar后&#xff0c;提交到flink v1.19.2集群进行运行。 2 环境准备 2.1 jdk和maven工具的安装 yum安装jdk 1.8&#xff1a; yum install java-1.8.0-openjdk-1.8.0.212.b04-0.el7_6.x86_64 java-1.8.0-ope…

    业务应用和大数据平台的数据流向

    概述 业务应用与大数据平台之间的交互是实现数据驱动决策和实时业务处理的关键环节。其交互方式多样&#xff0c;协议选择取决于数据流向、实时性要求及技术架构。一句话总结&#xff0c;数据流向可以是从业务应用写入大数据平台&#xff0c;也可以是大数据平台回写至业务应用…

    计算机毕业设计SpringBoot+Vue.jst网上超市系统(源码+LW文档+PPT+讲解)

    温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 作者简介&#xff1a;Java领…

    【无人集群系列---无人机集群编队算法】

    【无人集群系列---无人机集群编队算法】 一、核心目标二、主流编队控制方法1. 领航-跟随法&#xff08;Leader-Follower&#xff09;2. 虚拟结构法&#xff08;Virtual Structure&#xff09;3. 行为法&#xff08;Behavior-Based&#xff09;4. 人工势场法&#xff08;Artific…