Loading

Vue基础

一:条件渲染

指令 释义
v-if 相当于: if
v-else 相当于:else
v-else-if 相当于:else if
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>if、else if、else</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <h3>案例:if、else if、else</h3>
    <h2 v-if="type==='1'">A</h2>
    <h2 v-else-if="type==='2'">B</h2>
    <h2 v-else>C</h2>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            type: '1',
        }
    })
</script>
</html>

img

二:列表渲染

1. v-if+v-for+v-else控制购物车商品的显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-if + v-for + v-else控制购物车商品的显示</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="box">
    <h2>我的购物车</h2>
    <button @click="show">刷新购物车</button>
    <br><br>
    <table v-if="!shopping_car.length==0">
        <tr>
            <td>商品名称</td>
            <td>价格</td>
        </tr>
        <tr v-for="item in shopping_car">
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
        </tr>
    </table>
    <table v-else>
        <tr>
            <td>商品名称</td>
            <td>价格</td>
        </tr>
        <tr>
            <td>暂无信息</td>
            <td>暂无信息</td>
        </tr>
    </table>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            isActive: false,
            shopping_car: []
        },
        methods: {
            show() {
                this.shopping_car = [
                    {name: 'Threadripper 3990X', price: '29999元'},
                    {name: 'NVIDIA RTX 8000', price: '59999元'},
                    {name: 'ROG ZENITH II EXTREME', price: '9999元'},
                ]
            }
        }
    })
</script>
</html>

img

2. v-for遍历数组(列表)、对象(字典)、数字

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-for遍历数组(列表)、对象(字典)</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>

<div id="box">
    <h2>数组(列表)for循环遍历</h2>
    <ul>
        <li v-for="(value,index) in list_test">{{index}} —— {{value}}</li>
    </ul>

    <h2>对象(字典)for循环遍历</h2>
    <ul>
        <li v-for="(value,key) in dic_test">{{key}} —— {{value}}</li>
    </ul>

    <h2>数组(列表)套对象(字典)for循环遍历</h2>
    <table>
        <tr>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
            <td>国籍</td>
        </tr>
        <tr v-for="info in summary_test">
            <td>{{info.name}}</td>
            <td>{{info.age}}</td>
            <td>{{info.gender}}</td>
            <td>{{info.country}}</td>
        </tr>
    </table>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            list_test: ['First', 'second', 'Third', 'Forth', 'Fifth'],
            dic_test:{name: 'Darker', age: 18, gender: 'male'},
            summary_test: [
                    {name: 'Alan', age: 23, gender: 'male', country: 'America'},
                    {name: 'Ben', age: 15, gender: 'male', country: 'Australia'},
                    {name: 'Cindy', age: 12, gender: 'female', country: 'Japan'},
                    {name: 'Darker', age: 18, gender: 'male', country: 'China'},
                    {name: 'Elisa', age: 26, gender: 'female', country: 'Mexico'},
                ]
        }
    })
</script>
</html>

img

注意!Vue中:

  • 数组indexvalue反的
  • 对象keyvalue也是反的

3. key值 的解释

vue中使用的是虚拟DOM,会和原生的DOM进行比较,然后进行数据的更新,提高数据的刷新速度(虚拟DOM用了diff算法)

  • v-for循环数组、对象时,建议在控件/组件/标签写1个key属性,属性值唯一
  • 页面更新之后,会加速DOM的替换(渲染)
  • :key="变量"

4. 数组更新与检测

可以检测到变动的数组操作:
  • push:最后位置添加
  • pop:最后位置删除
  • shift:第一个位置删除
  • unshift:第一个位置添加
  • splice:切片
  • sort:排序
  • reverse:反转
检测不到变动的数组操作:
  • filter():过滤
  • concat():追加另一个数组
  • slice():
  • map():
原因:

作者重写了相关方法(只重写了一部分方法,但是还有另一部分没有重写)

解决方法:
// 方法1:通过 索引值 更新数组(数据会更新,但是页面不会发生改变)
vm.arrayList[0]
"Alan"
vm.arrayList[0]='Darker'
"Darker"

// 方法2:通过 Vue.set(对象, index/key, value) 更新数组(数据会更新,页面也会发生改变)
Vue.set(vm.arrayList, 0, 'Darker')

三:事件处理

事件 释义
input 当输入框进行输入的时候 触发的事件
change 当元素的值发生改变时 触发的事件
blur 当输入框失去焦点的时候 触发的事件

changeblur 最本质的区别:

  • 如果输入框为空,失去焦点后,change不会触发,但是blur会触发

1.过滤案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>过滤案例</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <p><input type="text" v-model="myText" @input="handleInput" placeholder="请输入要筛选的内容:"></p>
<!-- <p><input type="text" v-model="myText" @change="handleInput" placeholder="请输入要筛选的内容:"></p> -->
<!-- <p><input type="text" v-model="myText" @blur="handleInput" placeholder="请输入要筛选的内容:"></p> -->
    <ul>
        <li v-for="data in newList">{{data}}</li>
    </ul>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            myText: '',
            dataList: ['a', 'at', 'atom', 'be', 'beyond', 'cs', 'csrf'],
            newList: ['a', 'at', 'atom', 'be', 'beyond', 'cs', 'csrf'],
        },
        methods: {
            handleInput() {
                this.newList = this.dataList.filter(item => {
                    // item.indexOf(this.myText):输入框中输入的字符串在筛选元素中的索引
                    return item.indexOf(this.myText) > -1   // 返回索引大于1的元素:>-1 就表示包含在其中
                })
            },
        },
    })
</script>
</html>

img

2.事件修饰符

事件修饰符 释义
.stop 只处理自己的事件,父控件冒泡的事件不处理(阻止事件冒泡)
.self 只处理自己的事件,子控件冒泡的事件不处理
.prevent 阻止a链接的跳转
.once 事件只会触发一次(适用于抽奖页面)

使用修饰符时,顺序很重要;相应的代码会以同样的顺序产生

  • v-on:click.prevent.self 会阻止所有的点击
  • v-on:click.self.prevent 只会阻止对元素自身的点击
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件修饰符</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
<!--    <ul @click="handleUl">-->
    <ul @click.self="handleUl">
<!--        <li v-for="data in dataList" @click="handleLi">{{data}}</li>-->
        <li v-for="data in dataList" @click.stop="handleLi">{{data}}</li>
        <li><a href="http://www.baidu.com">不拦截</a></li>
        <li><a href="http://www.baidu.com" @click="handleLink($event)">点击拦截</a></li>
        <li><a href="https://www.baidu.com" @click.prevent="handleLink">点击拦截</a></li>
        <li><button @click.once="test">只执行一次</button></li>
    </ul>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: ['1','22','333','4444']
        },
        methods: {
            handleUl(ev){
                console.log('ul被点击了')
            },
            handleLi(){
                console.log('li被点击了')
                ev.stopPropagation()    // 点击事件停止 冒泡(向父组件传递时间)
            },
            handleLink(ev){
                ev.preventDefault()
            },
            test(){
                alert('只触发1次')
            }
        }
    })
</script>
</html>

[事件冒泡](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/01 click.gif)

[事件冒泡](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/01 click.gif)

[阻止事件冒泡](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/02 click1.gif)

[阻止事件冒泡](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/02 click1.gif)

[阻止链接跳转+只执行1次](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/02 prevent.gif)

[阻止链接跳转+只执行1次](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/02 prevent.gif)

3.按键修饰符

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>按键修饰符</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <!--    <input type="text" v-model="myInput" @keyup="handleKey">-->
    <!--    <input type="text" v-model="myInput" @keyup.13="handleKey">-->
    <input type="text" @keyup="handleKey1">
    <input type="text" @keyup.enter="handleKey2">
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: ['1', '22', '333', '4444']
        },
        methods: {
            handleKey1(ev) {
                console.log('按下了' + ev)
                // if (ev.keyCode==13){
                //     console.log('回车键被按下了')
                // }
            },
            handleKey2(ev) {
                console.log('按下了回车键')
            }
        }
    })
</script>
</html>

[img](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/04 key.gif)

四:数据双向绑定

v-model的使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <input type="text" v-model="myText" placeholder="请输入内容">
    您输入的内容是:{{myText}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            myText: '',
        },
    })
</script>
</html>

[img](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/03 v-model.gif)

五:表单控制

1.checkbox选中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>checkbox</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <input type="text" placeholder="请输入用户名:"><br>
    <input type="password" placeholder="请输入密码:"><br>
    <input type="checkbox" v-model="radio">记住用户名
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            myText: '',
            textBig: '',
            radio: false,
        },
    })
</script>
</html>

[img](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/05 checkbox.gif)

2.单选

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单选</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <input type="radio" v-model="radio" value="男">男
    <input type="radio" v-model="radio" value="女">女
    <input type="radio" v-model="radio" value="保密">保密
    <br><br>您选择的性别:{{radio}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            radio: '',
        },

    })
</script>
</html>

[img](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/0 radio.gif)

3.多选

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>多选</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">

    <input type="checkbox" v-model="many" value="篮球">篮球
    <input type="checkbox" v-model="many" value="足球">足球
    <input type="checkbox" v-model="many" value="棒球">棒球
    <input type="checkbox" v-model="many" value="桌球">桌球
    <br><br>您喜欢的球类:{{many}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            many: [],
        },
    })
</script>
</html>

[img](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/07 dx.gif)

4.购物车案例 - 结算

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>购物车结算</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="box">
    <table>
        <tr>
            <td>商品名称</td>
            <td>价格</td>
            <td>数量</td>
            <td>选择</td>
        </tr>
        <tr v-for="item in dataList">
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td>{{item.number}}</td>
            <td><input type="checkbox" :value="item" v-model="checkGroup"></td>
        </tr>
    </table>
    <br>已选商品:{{checkGroup}}
    <br>总价:{{getPrice()}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: [
                {name: '今瓶没', price: 99, number: 2},
                {name: '西柚记', price: 59, number: 1},
                {name: '水壶转', price: 89, number: 5},
            ],
            checkGroup: [],
        },
        methods: {
            getPrice() {
                let sum_price = 0
                for (i in this.checkGroup) {    // 这里的 i 是索引
                    sum_price += this.checkGroup[i]['number'] * this.checkGroup[i]['price']
                }
                return sum_price
            }
        }
    })
</script>
</html>

[img](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/08 gwc1.gif)

5.购物车案例 - 全选/全不选

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>全选/全不选</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="box">
    <table>
        <tr>
            <td>商品名称</td>
            <td>价格</td>
            <td>数量</td>
            <td>全选/全不选<input type="checkbox" v-model="allChecked" @change="checkAll"></td>
        </tr>
        <tr v-for="item in dataList">
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td>{{item.number}}</td>
            <td><input type="checkbox" :value="item" v-model="checkGroup" @change="checkOne"></td>
        </tr>
    </table>
    <br>已选商品:{{checkGroup}}
    <br>总价:{{getPrice()}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: [
                {name: '今瓶没', price: 99, number: 2},
                {name: '西柚记', price: 59, number: 1},
                {name: '水壶转', price: 89, number: 5},
            ],
            checkGroup: [],
            allChecked: false,
        },
        methods: {
            getPrice() {
                let sum_price = 0
                for (i in this.checkGroup) {    // 这里的 i 是索引
                    sum_price += this.checkGroup[i]['number'] * this.checkGroup[i]['price']
                }
                return sum_price
            },
            checkAll() {
                if (this.checkGroup.length > 0) {
                    this.checkGroup = []
                } else {
                    this.checkGroup = this.dataList
                }
            },
            checkOne() {
                // if (this.checkGroup.length === this.dataList.length) {
                //     this.allChecked = true
                // } else {
                //     this.allChecked = false
                // }
                this.allChecked = this.checkGroup.length === this.dataList.length;
            }
        }
    })
</script>
</html>

[img](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/09 gwc2.gif)

6.购物车案例 - 数量加减

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>控制加减</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row">
    <div id="box" class="col-md-4 offset-md-1 text-center mt-5 ">
        <table class="table table-bordered">
            <thead>
            <tr>
                <th scope="col">商品名称</th>
                <th scope="col">单价</th>
                <th scope="col">数量</th>
                <th scope="col">全选/全不选 <input type="checkbox" v-model="allChecked" @change="checkAll"></th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="item in dataList">
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td>
                    <button class="btn link btn-sm" @click="reduceNum(item)">-</button>
                    {{item.number}}
                    <button class="btn link btn-sm" @click="item.number++">+</button>
                </td>
                <td><input type="checkbox" :value="item" v-model="checkGroup" @change="checkOne"></td>
            </tr>
            <tr class="text-left">
                <td colspan="4">总价:{{getPrice()}}
            </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: [
                {name: '今瓶没', price: 99, number: 1},
                {name: '西柚记', price: 59, number: 1},
                {name: '水壶转', price: 89, number: 1},
            ],
            checkGroup: [],
            allChecked: false,
        },
        methods: {
            getPrice() {
                let sum_price = 0
                for (i in this.checkGroup) {
                    sum_price += this.checkGroup[i]['number'] * this.checkGroup[i]['price']
                }
                return sum_price
            },
            checkAll() {
                if (this.checkGroup.length > 0) {
                    this.checkGroup = []
                } else {
                    this.checkGroup = this.dataList
                }
            },
            checkOne() {
                // if (this.checkGroup.length === this.dataList.length) {
                //     this.allChecked = true
                // } else {
                //     this.allChecked = false
                // }
                this.allChecked = this.checkGroup.length === this.dataList.length;
            },
            reduceNum(item) {
                if (item.number === 1) {
                    item.number = 1
                } else {
                    item.number--
                }
            }
        }
    })
</script>
</html>

[img](https://darker-x.oss-cn-hangzhou.aliyuncs.com/img/gitee/11 gwc3.gif)

六:v-model进阶

v-model 之 lazy、number、trim

  • lazy:等待input框的数据绑定时区焦点之后再变化
  • number:数字开头,只保留数字,后面的字母不保留;字母开头,都保留
  • trim:去除首位的空格
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-model 之 lazy、number、trim</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <input type="text" v-model="myText1" placeholder="normal"> {{myText1}}
    <br>
    <input type="text" v-model.lazy="myText2" placeholder="lazy"> {{myText2}}
    <br>
    <input type="text" v-model.number="myText3" placeholder="number"> {{myText3}}
    <br>
    <input type="text" v-model.trim="myText4" placeholder="trim"> {{myText4}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            myText1: '',
            myText2: '',
            myText3: '',
            myText4: '',
        },
    })
</script>
</html>

img

posted @ 2021-04-25 15:53  吃了好多肉  阅读(104)  评论(0编辑  收藏  举报