彼方尚有荣光在|

_xiaolin

园龄:2年9个月粉丝:3关注:5

Vue(尚硅谷)

Vue(尚硅谷)

[Toc]

1、Vue简介

1、Vue是什么?

Vue是一套用于构建用户界面渐进式JavaScript框架

image-20220926231306867

渐进式:Vue可以自底向上逐层的应用,简单应用:只需一个轻量小巧的核心库,复杂应用:可以引入各式各样的Vue插件

2、谁开发的?

image-20220926231858685

后起之秀,生态完善,已然成为国内前端工程师必备技能。

3、Vue的特点

1、采用组件化模式,提高代码复用率,且让代码更好维护

image-20220926232333436

2、声明式编码,让编码人员无需直接操作DOM,提高开发效率

image-20220926232857542

image-20220926232912627

image-20220926233020869

3、使用虚拟DOM+优秀的Diff算法,尽量复用DOM节点

image-20220926233459138

还得写判断条件

image-20220926233533255

image-20220926233900020

4、学习Vue之前要掌握的JavaScript基础知识?

ES6语法规范

ES6模块化

包管理器

原型、原型链

数组常用方法

axios

promise

........

5、Vue官网

Vue2

Vue3

2、配置Vue环境

1、安装Vue.js

开发版本

生产版本

2、安装Vue开发者工具

Installation | Vue Devtools (vuejs.org)

谷歌浏览器使用下面链接搜索下载:

极简插件_Chrome扩展插件商店_优质crx应用下载 (zzzmh.cn)

3、阻止vue在启动时生成生产提提示

Vue.config.productionTip =false;

正常情况下在html页面用script标签写就可以了,
但是现在好像得在vue.js中修改,Vue3新版本移除了

3、初识Vue

<!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>初识vue</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
    <!-- 
        初识Vue:
        1、想让Vue工作,就必须创建一个Vue实例,且要传入一个配置对象;
        2、root容器里的代码依然符合html规范,只不过混入了一些特殊的Vue语法;
        3、root容器里的代码被称为【Vue模板】;
        4、容器和Vue实例是一对一关系(后面Vue有组件化)
        5、真实开发中只有一个vue实例,并且会配合着组件一起使用;
        6、{{xxx}}中要写js表达式,且xxx可以自动读取到data中的所有属性;
        7、一旦data中的数据发送改变,那么模板中用到数据的地方也会自动更新;

        注意区分:js表达式和js代码(语句)
            1、表达式:一个表达式会产生一个值,可以放在任何一个需要值的地方
                (1)a
                (2)a+b
                (3)demo(1)
                (4)x===y?'a':'b'

            2、js代码(语句)
                (1)if(){}
                (2)for(){}

     -->

    
    <!-- <div class="root">
        <h1>Hello, {{name}} 1</h1>
    </div>
    <div class="root">
        <h1>Hello, {{name}} 2</h1>
    </div> -->
    <!-- 准备好一个容器 -->
    <div id="root1">
        <h1>Hello, {{name.toUpperCase()}},{{address}},{{Date.now()}}</h1>

    </div>
    <!-- <div id="root2">
        <h1>Hello, {{name}},{{address}}</h1>
    </div> -->

    <script type="text/javascript">
        Vue.config.productionTip =false;//阻止vue在启动时生成生产提提示

        // 创建Vue实例
        new Vue({
            el:"#root1",  //el用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串。或者直接使用document.getxxxx
            data:{ //data中用于存储数据,数据供el所指定的容器去使用,值我们暂时先写成一个对象
                name:'我是Vue',
                address:"广州"
            }
        });

        /* new Vue({
            el:"#root2",  //el用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串。或者直接使用document.getxxxx
            data:{ //data中用于存储数据,数据供el所指定的容器去使用,值我们暂时先写成一个对象
                name:"HHH",
                address:"广东"
            }
        }); */
        
    </script>

</body>
</html>

4、Vue模板语法

<!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="../js/vue.js"></script>
</head>
<body>

    <!-- 
        Vue模板语法有两大类:
            1、插值语法:
                功能:用于解析标签体内容
                写法:{{xxx}},xxx是js表达式,且可以直接读取到data中的所有属性
            2、指令语法:
                功能:用于解析标签(包括:标签属性、标签体内容、绑定事件......)
                举例:v-bind:href="xxx" 或者简写为 :href="xxx",xxx同样要写js表达式
                    且可以直接读取到data中的所有属性
                备注:Vue中有很多指令,功能都大不相同,且形式都是:v-????,此处只是讲了一个v-bind作为例子

     -->
    <!-- 准备好一个容器 -->
    <div id="root">
        <h1>插值语法</h1>
        <h3>你好,{{name}}</h3>
        <hr>
        <h1>指令语法</h1>
        <a v-bind:href="douyin.url.toUpperCase()" v-bind:x="hello">点我去看{{douyin.name}}</a>
        <!-- <a v-bind:href="url">点我去逛b站</a> -->
        <a :href="bilibili.url" x="hello">点我去逛{{bilibili.name}}</a>
    </div>
    
</body>
    <script>
        Vue.config.productionTip=false;//阻止Vue启动时生成生产提示

        new Vue({
            el:"#root",
            data:{
                name:"Jack",
                bilibili:{
                    name:"b站",
                    url:"https://www.bilibili.com"    
                },
                douyin:{
                    name:"抖音",
                    url:"https://www.douyin.com"
                },
                hello:'你好'
            }
        });
    </script>
</html>

data中可以使用对象分层级存放数据,取数据时按对象形式取即可

5、数据绑定

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        Vue中有两种数据绑定的方式:
            1、单向绑定(v-bind):数据只能从data流向页面
            2、双向绑定(v-model):数据不仅能从data流向页面,也能从页面流向data
            备注:
                1、双向绑定一般都应用于表单类元素上(如:input、select等)
                2、v-model:value可以简写为v-model,因为v-model默认收集的就是value值。

     -->
    <!-- 准备好一个容器 -->
    <div id="root">
        <!-- 普通写法 -->
        <!-- 单项数据绑定:<input type="text" v-bind:value="name"><br> -->
        <!-- 双向数据绑定:<input type="text" v-model:value="name"><br> -->

        <!-- 简写 -->
        单项数据绑定:<input type="text" :value="name"><br>
        双向数据绑定:<input type="text" v-model="name"><br>
        <!-- 如下代码是错误的,因为v-model只能应用在表单类元素(输入类元素)上 -->
        <!-- <h2 v-model:x="name">你好</h2> -->
    </div>
</body>
    <script>
        new Vue({
            el:"#root",
            data:{
                name:"Vue"
            }
        })
    </script>
</html>

6、el与data的两种写法

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        data和el有两种写法:
            1、el有两种写法
                ①new Vue的时候配置el属性
                ②先创建Vue实例,随后通过vm.$mount("#root")指定el的值
            2、data有两种写法
                ①对象式
                ②函数式
                如何选择:目前哪种写法都可以,以后学习到组件时,data必须使用函数式,否则会报错
            3、一个重要原则:
                由vue管理的函数:一定不要写箭头函数,一旦写了箭头函数,this就不再是Vue实例了
                

     -->
    <!-- 准备一个容器 -->
    <div id="root">
        <h1>你好,{{name}}</h1>
    </div>
</body>
    <script>
        /* const v = new Vue({ 
            // 第一种写法
            // el:'#root',
            data:{
                name:"Vue"
            }
        });
        console.log(v);
        // 第二种写法,mount挂载
        v.$mount('#root'); */


        new Vue({ 
            el:'#root',
            // data第一种写法:对象式
            /* data:{
                name:"Vue"
            } */

            // data的第二种写法:函数式
            data(){
                console.log(this);//此处的this是Vue实例对象
                return{
                    name:"Vue"
                }
            }
        });

    </script>
</html>

7、MVVM模型

1、M:模型(Model):对象data中的数据

2、V:视图(View):模板

3、VM:视图模型(View Model):Vue实例对象

image-20221102103126312

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        MVVM模型:
            1、M:模型(Model):对象data中的数据
            2、V:视图(View):模板
            3、VM:视图模型(View Model):Vue实例对象
        观察发现:
            1、data中所有属性,最后都出现在了vm身上
            2、vm身上所有的属性,及Vue原型上所有属性,在Vue模板中都可以直接使用

     -->
    <!-- 准备一个容器 -->
    <div id="root">
        <h1>学校名称:{{name}}</h1>
        <h1>学校地址:{{address}}</h1>
        <!-- <h1>测试一下1:{{1+1}}</h1>
        <h1>测试一下2:{{$options}}</h1>
        <h1>测试一下3:{{$emit}}</h1>
        <h1>测试一下4:{{_c}}</h1> -->
    </div>
</body>
    <script>
        const vm = new Vue({ 
            el:'#root',
            data:{
                name:"广东财经大学",
                address:"广州"
            }
        });

        console.log(vm);
        
    </script>
</html>

8、数据代理

1、回顾Object.defineProperty()方法

<!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>
</head>
<body>
    <script>
        let number = 18;
        let person={
            name:"张三",
            sex:"男",
            // age:18,
            // age:number
        };

        Object.defineProperty(person,'age',{
            // value:18,
            // enumerable:true, //设置属性是否可枚举,默认值是false
            // writable:true, //设置属性是否可以被修改,默认值是false
            // configurable:true //设置属性是否可以被删除,默认值是false

            // 当有人读取person的age属性时,get(getter)函数就会被调用,且返回值就是age的值
            get(){
                console.log("有人读取age属性了");
                return number;
            },
            // 当有人修改person的age属性时,set(setter)函数就会被调用,且会收到修改后的具体值
            set(value){
                console.log("有人修改了age属性,且值是:"+value);
                number=value;
            }

        });

        // console.log(Object.keys(person));
        /* for (const key in person) {
            console.log(person[key]);
        } */

        console.log(person);
    </script>
</body>
</html>

2、何为数据代理

<!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>
</head>
<body>
    <!-- 数据代理:通过一个对象代理对另外一个对象中的属性的操作(读/写) -->
    <script>
        let obj = {x:100};
        let obj2 = {y:200};
        Object.defineProperty(obj2,'x',{
            get(){
                return obj.x;
            },
            set(value){
                obj.x=value;
            }
        }) ;
    </script>
</body>
</html>

3、Vue中的数据代理

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        1、Vue中的数据代理:
            通过vm对象来代理data对象中属性的操作(读/写)
        2、Vue中数据代理的好处:
            更加方便的操作data中的数据
        3、基本原理:
            通过Object.defineProperty()把data对象中所有属性添加到vm上
            为每一个添加到vm上的属性,都指定一个getter/setter
            在getter/setter内部去操作(读/写)data中对应的属性
     -->
    <!-- 准备一个容器 -->
    <div id="root">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
    </div>
</body>
    <script>
        /* let data = {
            name:"广东财经大学",
            address:"广州"
        } */
        const vm = new Vue({ 
            el:'#root',
            data:{
                name:"广东财经大学",
                address:"广州"
            }
            // data
        });
        
    </script>
</html>

image-20221102113316344

9、事件处理

1、事件的基本使用

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        事件的基本使用:
            1、使用v-on:xxx 或@xxx绑定事件,其中xxx是事件名
            2、事件的回调需要配置在methods对象中,最终会在vm上
            3、methods中配置的函数,不要用箭头函数,否则this就不是vm了
            4、methods中配置的函数,都是被Vue所管理的函数,this的指向就是vm或组件实例对象
            5、@click="demo"和 @click="demo($event)"效果一致,但是后者可以传参

     -->
    <div id="root">
        <h2>欢迎来{{name}}学习Vue!</h2>
        <!-- <button v-on:click="showInfo">点我获取提示</button> -->
        <button @click="showInfo1">点我获取提示1(不传参)</button>
        <button @click="showInfo2(66,$event)">点我获取提示2(传参)</button>
    </div>
</body>
    <script>
        /* function showInfo(){
            alert("你好,欢迎呀");
        } */
        const vm = new Vue({ 
            el:'#root',
            data:{
                name:"b站"
            },
            methods:{
                showInfo1(event){
                    event = event || window.event;
                    // console.log(event.target.innerText);
                    // console.log(this);//此处this是Vue实例对象
                    // console.log(this==vm);//true
                    alert("你好,欢迎呀!");
                },
                showInfo2(number,event){
                    console.log(number,event);
                    alert("你好,欢迎呀!!");
                }
            }
        });
        
    </script>
</html>

2、事件修饰符

<!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="../js/vue.js"></script>
    <style>
        *{
            margin-top: 20px;
        }
        .demo1{
            height: 50px;
            background-color: #bfa;
        }
        .box1{
            padding: 5px;
            background-color: yellowgreen;
        }
        .box2{
            padding: 5px;
            background-color: yellow;
        }
        .list{
            width: 200px;
            height: 200px;
            background-color: skyblue;
            overflow: auto;
        }
        li{
            height: 100px;
        }
    </style>
</head>
<body>
    <!-- 
        Vue中的事件修饰符:
            1、prevent:阻止默认事件(常用)
            2、stop:阻止事件冒泡(常用)
            3、once:事件只触发一次(常用)
            4、capture:使用事件的捕获方式
            5、self:只有event.taegent是当前操作的元素时才触发事件
            6、passive:事件的默认认为立即执行,无需等待事件回调执行完毕


     -->
    <div id="root">
        <h2>欢迎来到{{name}}学习Vue!</h2>
        <!-- prevent:阻止默认事件(常用)  -->
        <a href="https://www.bilibili.com" @click.prevent="showInfo">点我提示信息</a>

        <!-- stop:阻止事件冒泡(常用)  -->
        <div class="demo1" @click="showInfo">
            <button @click.stop="showInfo">点我一下</button>
        </div>

        <!-- once:事件只触发一次(常用) -->
        <button @click.once="showInfo">点我一下</button>

        <!-- capture:使用事件的捕获方式 -->
        <div class="box1" @click.capture="showMsg('box1')">
            div1
            <div class="box2" @click="showMsg('box2')">
                div2
            </div>
        </div>

        <!-- self:只有event.taegent是当前操作的元素时才触发事件 -->
        <div class="demo1" @click.self="showInfo">
            <button @click="showInfo">点我一下</button>
        </div>

        <!-- passive:事件的默认认为立即执行,无需等待事件回调执行完毕 -->
        <ul @scroll="demo1" class="list">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
        </ul>
        <ul @wheel.passive="demo2" class="list">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
        </ul>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                name:"b站"
            },
            methods:{
                showInfo(e){
                    // e.stopPropagation();//阻止冒泡
                    // e.cancelBubble=true;//阻止冒泡
                    // e.preventDefault();//取消默认行为
                    console.log(e.target);
                    alert("你好呀!");
                },
                showMsg(msg){
                    console.log("你好"+msg);
                },
                demo1(){
                    
                    console.log("滚动了1");
                },
                demo2(){
                    for(let i=0;i<100000;i++){
                        console.log("#");
                    }
                    console.log("累坏了");
                    console.log("滚动了2");
                }
            }
        });
        
    </script>
</html>

3、键盘事件

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        1、Vue常用的按键别名:
            1、回车=>enter
            2、删除=>delete (捕获“删除”和“退格”键)
            3、退出=>esc
            4、空格=>space
            5、换行=>tab(特殊,必须配合keydown去使用)
            6、上=>up
            7、下=>down
            8、左=>left
            9、右=>right

        2、Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名)
        
        3、系统修饰键(用法特殊):ctrl、alt、shift、meta(window)
            (1).配合keyup使用,按下修饰符的同时按下其他键,随后释放其他键,事件才会被触发
            (2).配合keydown使用:正常触发事件

        4、也可以使用keyCode去指定具体的按键(不推荐)

        5、Vue.config.keyCodes.自定义键名 = 键码。可以定制按键别名
     -->
    <div id="root">
        <h2>欢迎来到{{name}}学习Vue!</h2>
        <input type="text" placeholder="按下回车提示输入" @keyup.huiche="showInfo">
    </div>
</body>
    <script>
        Vue.config.keyCodes.huiche=[13,65];//可以指定数组


        new Vue({ 
            el:'#root',
            data:{
                name:"b站"
            },
            methods:{
                showInfo(e){
                    console.log(e.key,e.keyCode);
                    // if(e.keyCode!==13) return;
                    console.log(e.target.value);
                }
            }
        });
        
    </script>
</html>

4、事件总结

修饰符是可以连着写的,注意顺序有别!

给键盘事件绑定时,可以连着绑定多个键名,代表一起时才生效!

10、计算属性

1、姓名案例----插值语法实现

<!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="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        姓:<input type="text" v-model="firstName"><br><br>
        名:<input type="text" v-model="lastName"><br><br>
        <!-- 姓名:<span>{{firstName+"-"+lastName}}</span> -->
        姓名:<span>{{firstName.slice(0,3)}}-{{lastName}}</span>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                firstName:"张",
                lastName:"三"
            }
        });
        
    </script>
</html>

2、姓名案例----methods实现

<!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="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        姓:<input type="text" v-model="firstName"><br><br>
        名:<input type="text" v-model="lastName"><br><br>
        <!-- 姓名:<span>{{firstName+"-"+lastName}}</span> -->
        姓名:<span>{{getFullName()}}</span>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                firstName:"张",
                lastName:"三"
            },
            methods:{
                getFullName(){
                    console.log("执行getFullName");
                    return this.firstName.slice(0,3)+'-'+this.lastName;
                }
            }
        });
        
    </script>
</html>

3、姓名案例---计算属性实现

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        计算属性:
            1、定义:要用的属性不存在,要通过已有属性计算得来
            2、原理:底层借助了Object.defineproperty方法提供的getter和setter
            3、get函数声明时候执行?
                (1)初次读取时会执行一次
                (2)当依赖的数据发生改变时会被再次被调用
            4、优势:与methods实现相比,内部有缓存机制(复用),效率更高,调试方便
            5、备注:
                1、计算属性最终会出现在vm上,直接读取使用即可
                2、如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发送改变

     -->
    <div id="root">
        姓:<input type="text" v-model="firstName"><br><br>
        名:<input type="text" v-model="lastName"><br><br>
        <!-- 姓名:<span>{{firstName+"-"+lastName}}</span> -->
        <!-- 有缓存机制,只调用一次get -->
        姓名:<span>{{fullName}}</span><br><br>
        <!-- 姓名:<span>{{fullName}}</span><br><br> -->
        <!-- 姓名:<span>{{fullName}}</span><br><br> -->
    </div>
</body>
    <script>
       const vm = new Vue({ 
            el:'#root',
            data:{
                firstName:"张",
                lastName:"三"
            },
            computed:{
                /* 
                    vm中存在的fullName是保存了调用get得到的返回值同名属性,而不是直接将此处的fullName放到vm中
                */
                fullName:{
                    // get有什么作用?
                    // 当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
                    // get什么时候调用?
                    /* 
                        1、初次读取fullName时
                        2、所依赖的数据发生变化时
                    */
                    get(){
                        console.log("get被调用了");
                        return this.firstName+'-'+this.lastName;
                    },
                    /* 
                        set什么时候调用,当fullName被修改时
                    */
                    set(value){
                        console.log("set被调用了");
                        const arr =value.split("-");
                        this.firstName=arr[0];
                        this.lastName=arr[1];
                    }
                }
            }
        });

        console.log(vm);
        
    </script>
</html>

4、姓名案例---计算属性简写

<!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="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        姓:<input type="text" v-model="firstName"><br><br>
        名:<input type="text" v-model="lastName"><br><br>
        姓名:<span>{{fullName}}</span><br><br>
    </div>
</body>
    <script>
       const vm = new Vue({ 
            el:'#root',
            data:{
                firstName:"张",
                lastName:"三"
            },
            computed:{
                // 完整写法
                /* fullName:{
                    
                    get(){
                        console.log("get被调用了");
                        return this.firstName+'-'+this.lastName;
                    },
                    set(value){
                        console.log("set被调用了");
                        const arr =value.split("-");
                        this.firstName=arr[0];
                        this.lastName=arr[1];
                    }
                } */
                // 简写
                fullName(){
                    console.log("get被调用了");
                    return this.firstName+'-'+this.lastName;
                }
            }
        });
        console.log(vm);
    </script>
</html>

11、监视属性

1、天气案例

<!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="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        <!-- <h2>今天天气很{{isHot?"炎热":"凉爽"}}</h2> -->
        <h2>今天天气很{{info}},{{x}}</h2>
        <!-- 事件@xxx="yyy" yyy可以写一些简单的语句 -->
         <!-- <button 绑定事件的时候 @click="changeWeather">切换天气</button> -->
         <!-- <button @click="isHot=!isHot">切换天气</button> -->
         <button @click="window.alert(1)">切换天气</button>
    </div>
</body>
    <script>
        const vm = new Vue({
            el:"#root",
            data:{
                isHot:true,
                x:1,
                window
            },
            computed:{
                info(){
                    return this.isHot?"炎热":"凉爽";
                }
            },
            methods: {
                /* changeWeather(){
                    this.isHot=!this.isHot;
                    this.x++;
                } */

            },
        });
        console.log(vm);
    </script>
</html>

2、天气案例----监视属性

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        1、当被监视的属性变化时,回调函数自动调用,进行相关操作
        2、监视的属性必须存在,才能进行监视
        3、监视的两种写法:
            (1)new Vue 时传入watch配置
            (2)通过vm.$watch监视

     -->
    <div id="root">
        <h2>今天天气很{{info}}</h2>
         <button @click="changeWeather">切换天气</button>
    </div>
</body>
    <script>
        const vm = new Vue({
            el:"#root",
            data:{
                isHot:true
            },
            computed:{
                info(){
                    return this.isHot?"炎热":"凉爽";
                }
            },
            methods: {
                changeWeather(){
                    this.isHot=!this.isHot;
                    this.x++;
                }

            },
            /* watch:{
                //也能监视info
                isHot:{
                    immediate:true,//初始化时让handler调用一下
                    // handler什么时候调用?当isHot发生改变时
                    handler(newValue,oldValue){
                        console.log("isHot被修改了",newValue,oldValue);
                    }
                }
            } */
        });
        vm.$watch('isHot',{
            immediate:true,//初始化时让handler调用一下
            // handler什么时候调用?当isHot发生改变时
            handler(newValue,oldValue){
            console.log("isHot被修改了",newValue,oldValue);
            }
        });
    </script>
</html>

3、深度监视

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        深度监视:
            (1)Vue中的watch默认不检测对象内部值的改变(一层)
            (2)配置deep:true可以监测对象内布值改变(多层)
        备注:
            (1)Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以
            (2)使用watch时可以根据数据的具体结构,决定是否采用深度监视
     -->
     <!-- 准备好一个容器 -->
    <div id="root">
        <h2>今天天气很{{info}}</h2>
         <button @click="changeWeather">切换天气</button>
         <hr>
         <h3>a的值是{{numbers.a}}</h3>
         <button @click="numbers.a++">点我让a加1</button>
         <h3>b的值是{{numbers.b}}</h3>
         <button @click="numbers.b++">点我让b加1</button>
         <button @click="numbers={a:666,b:999}">替换numbers</button>
         {{numbers.c.d.e}}
    </div>
</body>
    <script>
        const vm = new Vue({
            el:"#root",
            data:{
                isHot:true,
                numbers:{
                    a:1,
                    b:1,
                    c:{
                        d:{
                            e:100
                        }
                    }
                }
            },
            computed:{
                info(){
                    return this.isHot?"炎热":"凉爽";
                }
            },
            methods: {
                changeWeather(){
                    this.isHot=!this.isHot;
                    this.x++;
                }

            },
            watch:{
                //也能监视info
                isHot:{
                    // immediate:true,//初始化时让handler调用一下
                    // handler什么时候调用?当isHot发生改变时
                    handler(newValue,oldValue){
                        console.log("isHot被修改了",newValue,oldValue);
                    }
                },
                //监视多级结构中某个属性的变化
                /* 'numbers.a':{
                    handler(){
                        console.log("a被改变了");
                    }
                } */
                // 监视多级结构中所有属性的变化
                numbers:{
                    deep:true,
                    handler(){
                        console.log("numbers改变了");
                    }
                }
            }
        });
    </script>
</html>

4、深度监视---简写

<!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="../js/vue.js"></script>
</head>
<body>
  
    <div id="root">
        <h2>今天天气很{{info}}</h2>
         <button @click="changeWeather">切换天气</button>
    </div>
</body>
    <script>
        const vm = new Vue({
            el:"#root",
            data:{
                isHot:true,
            },
            computed:{
                info(){
                    return this.isHot?"炎热":"凉爽";
                }
            },
            methods: {
                changeWeather(){
                    this.isHot=!this.isHot;
                    this.x++;
                }

            },
            watch:{
                //也能监视info
                // 正常写法
                /* isHot:{
                    // deep:true,//深度监视
                    // immediate:true,//初始化时让handler调用一下
                    handler(newValue,oldValue){
                        console.log("isHot被修改了",newValue,oldValue);
                    }
                }, */
                // 简写
                /* isHot(newValue,oldValue){
                    console.log("isHot被修改了",newValue,oldValue);
                }, */
            }
        });

        // 正常写法
       /*  vm.$watch('isHot',{
                    // deep:true,//深度监视
                    // immediate:true,//初始化时让handler调用一下
                    handler(newValue,oldValue){
                        console.log("isHot被修改了",newValue,oldValue);
                    }
                }); */
            vm.$watch('isHot',function(newValue,oldValue){
                        console.log("isHot被修改了",newValue,oldValue);
                    });
    </script>
</html>

5、姓名案例--watch实现(监视和计算的区别)

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        computed和watch之间的区别:
            1、computed能完成的功能,watch都能完成
            2、watch能完成的功能,computed不一定能完成,例如:watch可以进行异步操作
        两个重要小原则:
            1、所有被Vue管理的函数,最好写成普通函数,这样this的指向才是vm或组件实例对象
            2、所有不被Vue管理的函数(定时器的回调函数、ajax的回调函数、Promise的回调函数等),最好都写成箭头函数
            这样this的指向才是vm或组件实例对象
     -->
    <div id="root">
        姓:<input type="text" v-model="firstName"><br><br>
        名:<input type="text" v-model="lastName"><br><br>
        姓名:<span>{{fullName}}</span><br><br>
    </div>
</body>
    <script>
       const vm = new Vue({ 
            el:'#root',
            data:{
                firstName:"张",
                lastName:"三",
                fullName:"张-三"
            },
            watch:{
                firstName(newValue){
                    //可以实现异步操作
                    // 定时器由js引擎调用
                    /* setTimeout(()=>{
                        this.fullName = newValue+"-"+this.lastName;
                    },1000); */
                    this.fullName = newValue+"-"+this.lastName;
                },
                lastName(newValue){
                    this.fullName = this.firstName+"-"+newValue;
                },
            }
        });
    </script>
</html>

12、绑定样式

<!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>
    <style>
        .basic{
            width: 400px;
            height: 100px;
            border: 1px solid black;
        }
        
        .happy{
            border: 4px solid red;;
            background-color: rgba(255, 255, 0, 0.644);
            background: linear-gradient(30deg,yellow,pink,orange,yellow);
        }
        .sad{
            border: 4px dashed rgb(2, 197, 2);
            background-color: gray;
        }
        .normal{
            background-color: skyblue;
        }

        .atguigu1{
            background-color: yellowgreen;
        }
        .atguigu2{
            font-size: 30px;
            text-shadow:2px 2px 10px red;
        }
        .atguigu3{
            border-radius: 20px;
        }
    </style>
    <script src="../js/vue.js"></script>
</head>
<body>
    <!-- 
        绑定样式:
            1、class样式
                写法:class="xxx" xxx可以是字符串、对象、数组
                    字符串写法适用于:类名不确定,要动态获取
                    对象写法适用于:要绑定多个样式,个数不确定,名字也不确定
                    数组写法适用于:要绑定多个样式,个数确定,名字确定,1但是不确定用不用
            2、style样式
                :style="{fontSize:xxx"}"其中xxx是动态值
                :style="[a,b]" 其中a,b是样式对象
     -->
    <div id="root">
        <!-- 绑定class样式---字符串写法,适用于:样式的类名不确定,需要动态指定 -->
        <div class="basic" :class="mood" @click="changeMood">{{name}}</div>
        <br><br>
        <!-- 绑定class样式---数组写法,适用于:要绑定的样式个数不确定,名字也不确定 -->
        <div class="basic" :class="classArr">{{name}}</div>
        <br><br>
        <!-- 绑定class样式---对象写法,适用于:要绑定的样式个数确定,名字也确定,但要动态决定用不用 -->
        <div class="basic" :class="classObj">{{name}}</div>
        <br><br>
        <!-- <div class="basic" :style="{fontSize:fsize+'px'}">{{name}}</div> -->
        <!-- 绑定style---对象写法 -->
        <div class="basic" :style="styleObj">{{name}}</div>
        <br><br>
        <!-- 绑定style---数组写法 -->
        <div class="basic" :style="[styleObj,styleObj2]">{{name}}</div>
        <br><br>
        <div class="basic" :style="styleArr">{{name}}</div>
    </div>
</body>
    <script>
        const vm = new Vue({ 
            el:'#root',
            data:{
                name:"Vue",
                mood:'normal',
                classArr:['atguigu1','atguigu2','atguigu3'],
                classObj:{
                    atguigu1:false,
                    atguigu2:false,
                },
                // fsize:40
                styleObj:{
                    fontSize:'40px',
                    color:'red',
                    // backgroundColor:'yellow',
                },
                styleObj2:{
                    /* fontSize:'40px',
                    color:'red', */
                    backgroundColor:'yellow',
                },
                styleArr:[
                    {
                        fontSize:'40px',
                        color:'blue',
                        backgroundColor:'green',
                    },
                ]
            },
            methods: {
                changeMood(){
                    const arr = ['happy','sad','normal'];
                    let i =Math.floor(Math.random()*3);
                    console.log(i);
                    this.mood=arr[i];
                }
            },
        });
        
    </script>
</html>

13、条件渲染

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        条件渲染:
            1、v-if
                写法:
                    (1)v-if="表达式"
                    (2)v-else-if="表达式"
                    (3)v-else="表达式"
                    适用于:切换频率较低的场景
                    特点:不展示的DOM元素直接被移除
                    注意:v-if可以和v-else-if、v-else一起使用,但要求结构不能被打断
            2、v-show
                写法:v-show="表达式"
                适用于:切换频率较高的场景
                特点:不展示的DOM元素未被移除,仅仅是使用样式进行隐藏
            3、备注:使用v-if时,元素可能无法获取到,而使用v-show一定可以获取到
     -->
    <div id="root">
        <h2>当前的n值是{{n}}</h2>
        <button @click="n++">点我n+1</button>
        <!-- 使用v-show做条件渲染---display=none -->
        <!-- <h2 v-show="false">欢迎来到{{name}}</h2> -->
        <!-- <h2 v-show="1===1">欢迎来到{{name}}</h2> -->

        <!-- 使用v-if做条件渲染---直接删除页面结构 -->
        <!-- <h2 v-if="false">欢迎来到{{name}}</h2> -->
        <!-- <h2 v-if="1===1">欢迎来到{{name}}</h2> -->

        <!-- <div v-show="n===1">Angular</div>
        <div v-show="n===2">React</div>
        <div v-show="n===3">Vue</div> -->

        <!-- v-else和v-else-if -->
        <!-- <div v-if="n===1">Angular</div>
        <div v-else-if="n===2">React</div>
        <div v-else-if="n===3">Vue</div>
        <div v-else>其他都是我</div> -->

        <!-- <div v-show="n===1">
            <h2>你好</h2>
            <h2>Vue</h2>
            <h2>Hhhhh</h2>
        </div> -->

        <!-- 只能写v-if与template配合使用 -->
        <template v-if="n===1">
            <h2>你好</h2>
            <h2>Vue</h2>
            <h2>Hhhhh</h2>
        </template>
        
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                name:"Vue",
                n:0,
            }
        });
        
    </script>
</html>

14、列表渲染

1、基本列表

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        v-for
            1、用于展示列表数据
            2、语法:v-for="(item,index) in xxx" :key="yyy"
            3、可遍历:数组、对象、字符串(用得少)、指定次数(用得少)
     -->
    <div id="root">
        <!-- 遍历数组 -->
        <h2>员工列表</h2>
        <ul>
            <li v-for="(p,index) in persons" :key="p.id">
                {{p.name}}-{{p.age}}-{{index}}
            </li>
        </ul>

        <!-- 遍历对象 -->
        <h2>汽车信息</h2>
        <ul>
            <li v-for="(value,k) in car" :key="k">
                {{k}}:{{value}}
            </li>
        </ul>

        <!-- 遍历字符串 -->
        <h2>测试遍历字符串</h2>
        <ul>
            <li v-for="(char,index) in str" :key="index">
                {{index}}:{{char}}
            </li>
        </ul>

        <!-- 遍历指定次数 -->
        <h2>测试遍历指定次数</h2>
        <ul>
            <li v-for="(number,index) in 5" :key="index">
                {{index}}:{{number}}
            </li>
        </ul>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                persons:[
                    {id:'001',name:'张三',age:18},             
                    {id:'002',name:'李四',age:19},                
                    {id:'003',name:'王五',age:20},                
                ],
                car:{
                    name:'奥迪A8',
                    price: '70w',
                    color:'黑色'
                },
                str:'hello',
            }
        });
        
    </script>
</html>

2、key的原理

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        面试题:react、vue中的key有什么作用,(key的内部原理)
            1、虚拟DOM中key的作用:
                key是虚拟DOM对象的标识,当状态中的数据发送变化时,Vue会根据【新数据生成【新的虚拟DOM】
                随后Vue进行【新虚拟DOM】和【旧虚拟DOM】的差异比较,比较规则如下:
            2、对比规则:
                (1)旧虚拟DOM中找到了与新虚拟DOM相同的key:
                    ①若虚拟DOM中内容吗没变,直接使用之前的真实DOM
                    ②若虚拟DOM中的内容变了,则生成新的真实DOM,随后替换掉页面中之前的真实DOM
                (2)就虚拟DOM中未找到与新虚拟DOM相同的key
                    创建新的真实DOM,随后渲染到页面
            3、用index作为key可能会引发的问题:
                1、若对数据进行:逆序添加、逆序删除等破坏顺序的操作:
                    会产生没有必要的真实DOM更新==>界面效果没问题,但是效率低
                2、如果结构中还包含输入类的DOM:
                    会产生错误的DOM更新==>界面有问题
            4、开发中如何选择key:
                1、最好使用每条数据的唯一标识作为key,比如id、手机号、身份证号、学号等唯一值
                2、如果不存在对数据的逆序添加、逆序删除等破坏顺序操作,仅用于渲染列表用于展示,
                    使用index作为key是没有问题的。
     -->
    <div id="root">
        <!-- 遍历数组 -->
        <h2>员工列表</h2>
        <button @click.once="add">在开头添加一个老刘</button>
        <ul>
            <li v-for="(p,index) in persons" :key="p.id">
                {{p.name}}-{{p.age}}-{{index}}
                <input type="text">
            </li>
        </ul>

       
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                persons:[
                    {id:'001',name:'张三',age:18},             
                    {id:'002',name:'李四',age:19},                
                    {id:'003',name:'王五',age:20},                
                ],
            },
            methods: {
                add(){
                    const p = {id:'004',name:"老刘",age:40};
                    this.persons.unshift(p);
                }
            },
        });
        
    </script>
</html>

image-20221105104109743

image-20221105104617378

3、列表的过滤

/*
    filter()方法使用指定的函数测试所有元素,并创建一个包含所有通过测试的元素的新数组。

    filter()基本语法:
       arr.filter(callback[, thisArg])

   filter()参数介绍:
      参数名    说明
      callback   用来测试数组的每个元素的函数。调用时使用参数 (element, index, array)
      返回true表示保留该元素(通过测试),false则不保留。
      thisArg    可选。执行 callback 时的用于 this 的值。

  filter()用法说明:

    filter 为数组中的每个元素调用一次 callback 函数,并利用所有使得 callback 返回 true 或 等价于 true 的值 的元素创建一个新数组。
    callback 只会在已经赋值的索引上被调用,对于那些已经被删除或者从未被赋值的索引不会被调用。那些没有通过 callback 测试的元素会被跳过,不会被包含在新数组中。

    callback 被调用时传入三个参数:

    元素的值
    元素的索引
    被遍历的数组
    如果为 filter 提供一个 thisArg 参数,则它会被作为 callback 被调用时的 this 值。否则,callback 的this 值在非严格模式下将是全局对象,严格模式下为 undefined。

    filter 不会改变原数组。

    filter 遍历的元素范围在第一次调用 callback 之前就已经确定了。在调用 filter 之后被添加到数组中的元素不会被 filter 遍历到。
    如果已经存在的元素被改变了,则他们传入 callback 的值是 filter 遍历到它们那一刻的值。被删除或从来未被赋值的元素不会被遍历到。

*/
<!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="../js/vue.js"></script>
</head>
<body>

    <div id="root">
        <h2>员工列表</h2>
        <input type="text" placeholder="请输入名字" v-model="keyword">
        <ul>
            <li v-for="(p,index) in filterPersons" :key="p.id">
                {{p.name}}-{{p.age}}-{{p.sex}}
            </li>
        </ul>
    </div>
</body>
    <script>
        // 用watch实现
        /* new Vue({ 
            el:'#root',
            data:{
                keyword:'',
                persons:[
                    {id:'001',name:'马冬梅',age:18,sex:'女'},             
                    {id:'002',name:'周冬雨',age:19,sex:'女'},                
                    {id:'003',name:'周杰伦',age:20,sex:'男'},                
                    {id:'004',name:'温兆伦',age:21,sex:'男'},                
                ],
                filterPersons:[]
            },
            watch:{
                keyword:{
                    immediate:true,
                    handler(val){
                        // console.log("keyword被该了:"+newValue);
                        this.filterPersons = this.persons.filter((p)=>{
                            return p.name.indexOf(val)!==-1;
                        })
                    }
                }
                
            }
        }); */ 

        // 用computed实现
        new Vue({ 
            el:'#root',
            data:{
                keyword:'',
                persons:[
                    {id:'001',name:'马冬梅',age:18,sex:'女'},             
                    {id:'002',name:'周冬雨',age:19,sex:'女'},                
                    {id:'003',name:'周杰伦',age:20,sex:'男'},                
                    {id:'004',name:'温兆伦',age:21,sex:'男'},                
                ],
            },
            computed:{
                filterPersons(){
                    return this.persons.filter((p)=>{
                        return p.name.indexOf(this.keyword)!==-1
                    })
                }
            }
        });
        
    </script>
</html>

4、列表排序

<!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="../js/vue.js"></script>
</head>
<body>

    <div id="root">
        <h2>员工列表</h2>
        <input type="text" placeholder="请输入名字" v-model="keyword">
        <button @click="sortType=2">年龄升序</button>
        <button @click="sortType=1">年龄降序</button>
        <button @click="sortType=0">原顺序</button>
        <ul>
            <li v-for="(p,index) in filterPersons" :key="p.id">
                {{p.name}}-{{p.age}}-{{p.sex}}
            </li>
        </ul>
    </div>
</body>
    <script>         
        // 用computed实现
        new Vue({ 
            el:'#root',
            data:{
                keyword:'',
                sortType:0,//0原顺序,1降序,2升序
                persons:[
                    {id:'001',name:'马冬梅',age:28,sex:'女'},             
                    {id:'002',name:'周冬雨',age:19,sex:'女'},                
                    {id:'003',name:'周杰伦',age:30,sex:'男'},                
                    {id:'004',name:'温兆伦',age:11,sex:'男'},                
                ],
            },
            computed:{
                filterPersons(){
                    const arr= this.persons.filter((p)=>{
                        return p.name.indexOf(this.keyword)!==-1
                    });
                    // 判断是否需要排序
                    if(this.sortType){
                        arr.sort((p1,p2)=>{
                            // 升序
                            return this.sortType===2?p1.age-p2.age:p2.age-p1.age;
                        });
                    }
                    return arr;
                }
            }
        });
        
    </script>
</html>

5、更新数据时的一个问题

<!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="../js/vue.js"></script>
</head>
<body>

    <div id="root">
        <h2>员工列表</h2>
        <button @click="updateMei">更新马冬梅的信息</button>
        <ul>
            <li v-for="(p,index) in persons" :key="p.id">
                {{p.name}}-{{p.age}}-{{p.sex}}
            </li>
        </ul>
    </div>
</body>
    <script>         
        // 用computed实现
        const vm = new Vue({ 
            el:'#root',
            data:{
                persons:[
                    {id:'001',name:'马冬梅',age:28,sex:'女'},             
                    {id:'002',name:'周冬雨',age:19,sex:'女'},                
                    {id:'003',name:'周杰伦',age:30,sex:'男'},                
                    {id:'004',name:'温兆伦',age:11,sex:'男'},                
                ],
            },
            methods:{
                updateMei(){
                    /* this.persons[0].name='马老师';
                    this.persons[0].age=50;
                    this.persons[0].sex='男'; */  //奏效
                    /* this.persons[0]={
                        id:'001',
                        name:'马老师',
                        age:50,
                        sex:'男'
                    }; */
                    this.persons.splice(0,1,{id:'001',
                        name:'马老师',
                        age:50,
                        sex:'男'});
                }
            }
        });

        console.log(vm);
        
    </script>
</html>

6、Vue监测数据改变的原理

<!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="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
    </div>
</body>
    <script>
        const vm = new Vue({ 
            el:'#root',
            data:{
                name:'广东财经大学',
                address:'广州',
                student:{
                    name:'tom',
                    age:{
                        rage:40,
                        sage:18
                    },
                    friends:[
                        {
                            name:'jol',
                            age:19
                        }
                    ]
                }
            },
        });
        

    </script>
</html>

7、模拟一个数据的监测

<!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>
</head>
<body>
    <script>
        let data = {
            name:'广东财经大学',
            address:'广州'
        };
        
        // 创建一个监视的实例对象,用于监视data中属性的变化
        const obs = new Observer(data);

        console.log(obs);

        // 准备一个vm实例对象
        let vm = {}
        vm._data = data = obs;


        function Observer(obj){
            // 汇总对象中所有的属性形成一个数组
            const keys = Object.keys(obj);
            // 遍历
            keys.forEach((k)=>{
                Object.defineProperty(this,k,{
                    get(){
                        return obj[k];
                    },
                    set(val){
                        console.log(`${k}被改了,我要去解析模板,生成虚拟DOM.....`);
                        obj[k]=val;
                    }
                })
            })

        }


    </script>
</body>
</html>

8、Vue.set()的使用

<!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="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        <h1>学校信息</h1>
        <h2>学校名称:{{school.name}}</h2>
        <h2>学校地址:{{school.address}}</h2>
        <h2>校长:{{school.leader}}</h2>
        <hr>
        <h1>学生信息</h1>
        <button @click="addSex">添加一个性别属性,默认值男</button>
        <h2>姓名:{{student.name}}</h2>
        <h2 v-if="student.sex">性别:{{student.sex}}</h2>
        <h2>年龄: 真实:{{student.age.rage}},对外:{{student.age.sage}}</h2>
        <hr>
        <h2>朋友们</h2>
        <ul>
            <li v-for=" (f,index) in student.friends" :key="index">
                {{f.name}}--{{f.age}}
            </li>
        </ul>

    </div>
</body>
    <script>
        const vm = new Vue({ 
            el:'#root',
            data:{
                school:{
                    name:'广东财经大学',
                    address:'广州',
                },
                student:{
                    
                    name:'tom',
                    age:{
                        rage:40,
                        sage:18
                    },
                    friends:[
                        {
                            name:'jol',
                            age:19
                        },
                        {
                            name:'lili',
                            age:20
                        }
                    ]
                },
            },
            methods: {
                addSex(){
                    // Vue.set(this.student,'sex','男');
                    this.$set(this.student,'sex','男');
                },
            },
        });
        

    </script>
</html>

9、Vue监测数据改变的原理---数组

<!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="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        <h1>学校信息</h1>
        <h2>学校名称:{{school.name}}</h2>
        <h2>学校地址:{{school.address}}</h2>
        <h2>校长:{{school.leader}}</h2>
        <hr>
        <h1>学生信息</h1>
        <button @click="addSex">添加一个性别属性,默认值男</button>
        <h2>姓名:{{student.name}}</h2>
        <h2 v-if="student.sex">性别:{{student.sex}}</h2>
        <h2>年龄: 真实:{{student.age.rage}},对外:{{student.age.sage}}</h2>
        <hr>
        <h2>爱好</h2>
        <ul>
            <li v-for=" (h,index) in student.hobbies" :key="index">
                {{h}}
            </li>
        </ul>
        <h2>朋友们</h2>
        <ul>
            <li v-for=" (f,index) in student.friends" :key="index">
                {{f.name}}--{{f.age}}
            </li>
        </ul>

    </div>
</body>
    <script>
        const vm = new Vue({ 
            el:'#root',
            data:{
                school:{
                    name:'广东财经大学',
                    address:'广州',
                },
                student:{
                    
                    name:'tom',
                    age:{
                        rage:40,
                        sage:18
                    },
                    hobbies:[ '抽烟','喝酒','烫头'],
                    friends:[
                        {
                            name:'jol',
                            age:19
                        },
                        {
                            name:'lili',
                            age:20
                        }
                    ]
                },
            },
            methods: {
                addSex(){
                    // Vue.set(this.student,'sex','男');
                    this.$set(this.student,'sex','男');
                },
            },
        });
        

    </script>
</html>

10、总结Vue数据监测

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>总结数据监视</title>
		<style>
			button{
				margin-top: 10px;
			}
		</style>
		<!-- 引入Vue -->
		<script type="text/javascript" src="../js/vue.js"></script>
	</head>
	<body>
		<!--
			Vue监视数据的原理:
				1. vue会监视data中所有层次的数据。

				2. 如何监测对象中的数据?
								通过setter实现监视,且要在new Vue时就传入要监测的数据。
									(1).对象中后追加的属性,Vue默认不做响应式处理
									(2).如需给后添加的属性做响应式,请使用如下API:
													Vue.set(target,propertyName/index,value) 或 
													vm.$set(target,propertyName/index,value)

				3. 如何监测数组中的数据?
									通过包裹数组更新元素的方法实现,本质就是做了两件事:
										(1).调用原生对应的方法对数组进行更新。
										(2).重新解析模板,进而更新页面。

				4.在Vue修改数组中的某个元素一定要用如下方法:
							1.使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()
							2.Vue.set() 或 vm.$set()
				
				特别注意:Vue.set() 和 vm.$set() 不能给vm 或 vm的根数据对象 添加属性!!!
		-->
		<!-- 准备好一个容器-->
		<div id="root">
			<h1>学生信息</h1>
			<button @click="student.age++">年龄+1岁</button> <br/>
			<button @click="addSex">添加性别属性,默认值:男</button> <br/>
			<button @click="student.sex=='男' ? student.sex='女': student.sex='男' ">修改性别</button> <br/>
			<button @click="addFriend">在列表首位添加一个朋友</button> <br/>
			<button @click="updateFName">修改第一个朋友的名字为:张三</button> <br/>
			<button @click="addHobby">添加一个爱好</button> <br/>
			<button @click="updateFHobby">修改第一个爱好为:开车</button> <br/>
			<button @click="removeSmoke">过滤掉爱好中的抽烟</button> <br/>
			<h3>姓名:{{student.name}}</h3>
			<h3>年龄:{{student.age}}</h3>
			<h3 v-if="student.sex">性别:{{student.sex}}</h3>
			<h3>爱好:</h3>
			<ul>
				<li v-for="(h,index) in student.hobby" :key="index">
					{{h}}
				</li>
			</ul>
			<h3>朋友们:</h3>
			<ul>
				<li v-for="(f,index) in student.friends" :key="index">
					{{f.name}}--{{f.age}}
				</li>
			</ul>
		</div>
	</body>

	<script type="text/javascript">
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

		const vm = new Vue({
			el:'#root',
			data:{
				student:{
					name:'tom',
					age:18,
					hobby:['抽烟','喝酒','烫头'],
					friends:[
						{name:'jerry',age:35},
						{name:'tony',age:36}
					]
				}
			},
            methods: {
                addSex(){
                    // Vue.set(this.student,'sex','男');
                    this.$set(this.student,'sex','男');
                },
                addFriend(){
                    this.student.friends.unshift({name:'jack',age:23});
                },
                updateFName(){
                    this.student.friends[0].name='张三';
                },
                addHobby(){
                    this.student.hobby.unshift('学习');
                },
                updateFHobby(){
                    // this.student.hobby.splice(0,1,'开车');
                    // this.$set(this.student.hobby,0,'开车');
                    Vue.set(this.student.hobby,0,'开车');
                },
                removeSmoke(){
                    this.student.hobby = this.student.hobby.filter((h)=>{
                        return h!=='抽烟';
                    });
                }
            },
			
		})
	</script>
</html>

15、收集表单数据

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        收集表单数据:
            若:<input type="text"/>.则v-model收集的是value值,用户输入的就是value值
            若:<input type="radio"/>.则v-model收集的就是value值,且要给标签配置value值
            若:<input type="checkbox"/>
                1、没有配置input的value属性,那么收集的就是checked(勾选为true,未勾选为false)
                2、配置input的value属性:
                    (1)v-model的初始值是非数组,那么收集的就是checked(勾选为true,未勾选为false)
                    (2)v-model的初始值是数组,那么收集的就是value组成的数组
                3、备注:v-model的三个修饰符
                    lazy:失去焦点再收集数据
                    number:输入字符串转为有效的数字
                    trim:输入首尾空格过滤 
     -->
    <div id="root">
        <form @submit.prevent="demo">
            <!-- <label for="uno">账号: </label> -->
            <!-- <input type="text" id="uno"> -->
            账号:<input type="text" v-model.trim="userInfo.account"><br><br>
            密码:<input type="password" v-model.trim="userInfo.password"><br><br>
            年龄:<input type="number" v-model.number="userInfo.age"><br><br>
            性别:
            男<input type="radio" value="male" name="sex" v-model="userInfo.sex" ><input type="radio" value="female" name="sex" v-model="userInfo.sex"><br><br>
            爱好:
            学习<input type="checkbox" v-model="userInfo.hobby" value="study">
            打游戏<input type="checkbox" v-model="userInfo.hobby" value="game">
            打篮球<input type="checkbox" v-model="userInfo.hobby" value="basketball"><br><br>
            所属校区:
            <select v-model="userInfo.city">
                <option value="">请选择校区</option>
                <option value="beijing">北京</option>
                <option value="shanghai">上海</option>
                <option value="wuhan">武汉</option>
                <option value="shenzhen">深圳</option>
            </select><br><br>
            其他信息:
            <textarea v-model.lazy="userInfo.other"></textarea><br><br>
            <input type="checkbox" v-model="userInfo.agree">阅读并接受<a href="https://www.bilibili.com">《用户协议》</a>
            <button>提交</button>
        </form>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                userInfo:{
                    account:'',
                    password:'',
                    sex:'male',
                    age:'',
                    hobby:[],
                    city:'',
                    other:'',
                    agree:false
                },
            },
            methods: {
                demo(){
                    // alert(1);
                    console.log(JSON.stringify(this.userInfo));
                }
            },
        });
        
    </script>

</html>

16、过滤器

<!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="../js/vue.js"></script>
    <script src="../js/dayjs.min.js"></script>
</head>
<body>
    <!-- 
        过滤器:
            定义:要对显示的数据进行特定格式化后显示(适用于一些简单逻辑的处理)
            语法:
                1、注册过滤器:Vue.fliter(name,callback)或 new Vue(filters:{})
                2、使用过滤器:{{xxx | 过滤器名}} 或 v-bind:属性 = 'xxx | 过滤器名'
            备注:
                1、过滤器也可以接收额外参数、多个过滤器也可以串联
                2、并没有改变原本的数据,是产生新的对应的数据
            
     -->
    <div id="root">
        <h2>显示格式化后的时间</h2>
        <!-- 计算属性实现 -->
        <h3>现在是:{{fmTime}}</h3>
        <!-- methods实现 -->
        <h3>现在是:{{getFmTime()}}</h3>
        <!-- 过滤器实现 -->
        <h3>现在是:{{time | timeFormater}}</h3>
        <!-- 过滤器传参实现 -->
        <h3>现在是:{{time | timeFormater('YYYY-MM-DD')}}</h3>
        <!-- 多个过滤器传参实现 -->
        <h3>现在是:{{time | timeFormater('YYYY-MM-DD') | mySlice}}</h3>
        <h3 :x="msg | mySlice">尚硅谷</h3>
        <!-- 不允许以下形式 -->
        <!-- <input type="text" v-model="msg | mySlice"> -->
    </div>


    <div id="root2">
        <h2>{{msg | mySlice}}</h2>
    </div>
</body>
    <script>
        // 必须写在new Vue前
        Vue.filter('mySlice',function(value){
            return value.slice(0,4);
        });


        new Vue({ 
            el:'#root',
            data:{
                time:Date.now(),//时间戳
                msg:'你好,Vue!',
            },
            computed:{
                fmTime(){
                    return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss');
                }
            },
            methods:{
                getFmTime(){
                    return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss');
                }
            },
            filters:{
                timeFormater(value,str='YYYY年MM月DD日 HH:mm:ss'){
                    return dayjs(value).format(str);
                },
            }
        });


        new Vue({ 
            el:'#root2',
            data:{
                msg:'hello,Vue!',
            }
        });
        
     
    </script>
</html>

17、内置指令

1、v-text

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        我们学过的指令:
            v-bind:单向数据绑定解析表达式,可简写为:xxx
            v-model:双向数据绑定
            v-for:遍历数组/对象/字符串
            v-on:绑定事件监听,可简写为@
            v-if:条件渲染(动态控制节点是否存在)
            v-else:条件渲染(动态控制节点是否存在)
            v-show:条件渲染(动态控制节点是否展示)
        v-text指令:
            1、作用:向其所在的节点中渲染文本内容
            2、与插值语法的区别:v-text会替换掉节点的内容,{{xxx}}则不会
        
     -->
    <div id="root">
        <div>你好,{{name}}</div>
        <div v-text="name"></div>
        <div v-text="str"></div>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                name:'Vue',
                str:'<h3>你好!</h3>',
            }
        });
        
    </script>
</html>

2、v-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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        v-html指令:
            1、作用:向指定节点中渲染包含html结构的内容
            2、与插值语法的区别:
                (1)v-html会替换掉节点中所有的内容,{{xxx}}不会
                (2)v-html可以识别html结构
            3、严重注意:v-html有安全性问题!!!
                (1)在网站上动态渲染任意HTML是非常危险的,容易导致xss攻击
                (2)一定要在可信的内容上使用v-html,永不要用在用户提交的内容上!
                
     -->
    <div id="root">
        <div>你好,{{name}}</div>
        <div v-html="str"></div>
        <div v-html="str2"></div>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                name:'Vue',
                str:'<h3>你好!</h3>',
                str2:'<a href=javascript:location.href="https://www.bilibili.com?"+document.cookie>18禁!!!</a>',
            }
        });
        
    </script>
</html>

image-20221106110307531

3、v-cloak指令

<!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>
    <style>
        [v-cloak]{
            display: none;
        }
    </style>
    <!-- <script src="../js/vue.js"></script> -->
</head>
<body>
    <!-- 
        v-cloak指令(无值):
            1、本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-vloak属性
            2、使用css配合v-cloak可以解决网速慢时页面显示出{{XXX}}的问题
     -->
    <div id="root">
        <!-- vue接管容器后,v-cloak就会被删除,样式失效,重新显示 -->
        <h2 v-cloak>{{name}}</h2>
    </div>
    <script src="../js/vue.js"></script>//加载慢5s

</body>
    <script>
        console.log(1);
        new Vue({ 
            el:'#root',
            data:{
                name:'Vue'
            }
        });
        
    </script>
</html>

4、v-once

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        v-once指令:
            1、v-once所在节点在初次动态渲染后,就视为静态内容了
            2、以后数据的改变不会引起v-once所在结构的更新,可以用于优化性能
     -->
    <div id="root">
        <h2 v-once>初识化的n值:{{n}}</h2>
        <h2>当前的n值是:{{n}}</h2>
        <button @click="n++">点我n+1</button>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                n:1,

            }
        });
        
    </script>
</html>

5、v-pre指令

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        v-pre指令:
            1、跳过所在节点的编译的过程
            2、可利用它跳过:没有使用指令语法、插值语法的节点,会加快编译
     -->
    <div id="root">
        <h2 v-pre>Vue其实很简单</h2>
        <h2>当前的n值是:{{n}}</h2>
        <button @click="n++">点我n+1</button>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                n:1
            }
        });
        
    </script>
</html>

18、自定义指令

1、函数式

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍
     -->
     <div id="root">
       <h2>当前的n值是:<span v-text="n"></span></h2> 
       <h2>放大10倍后的n值是:<span v-big="n"></span></h2> 
       <button @click="n++">点我n+1</button>
     </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            data:{
                n:1,
            },
            directives:{
                /* big:{

                } */
                /* big:function(){

                } */
                // big函数何时被调用?
                // 1、指令与元素成功绑定时(一上来)2、指令所在的模板被重新解析时
                big(element,binding){
                    // console.log(element instanceof HTMLElement);
                    // console.log(element,binding.value);
                    element.innerText = binding.value*10;
                }
            }
        });
        
    </script>
</html>

2、对象式

<!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="../js/vue.js"></script>
</head>
<body>
    <!--  需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点 -->
    <div id="root">
        <input type="text" :value="n"><br><br>
        <input type="text" v-fbind:value="n"><br><br>
        <button @click="n++">点我n+1</button>
    </div>
    <br><br>
    <div id="root2">
        <input type="text" v-fbind:value="x">
    </div>
</body>
    <script>
        // 定义全局自定义指令
        Vue.directive('fbind',{
                bind(element,binding){
                    element.value=binding.value;
                },
                inserted(element,binding){
                    element.focus();
                },
                update(element,binding){
                    element.value=binding.value;
                }
            });





        new Vue({ 
            el:'#root',
            data:{
                n:1,
            },
            directives:{
                // 1、指令与元素成功绑定时(一上来)2、指令所在的模板被重新解析时
                /* fbind(element,binding){
                    element.value=binding.value;
                    element.focus();
                } */
                /* fbind:{
                    // 指令与元素成功绑定时(一上来)
                    // 下面的this都是window
                    bind(element,binding){
                        console.log('fbind-bind',this);
                        console.log('bind');
                        element.value=binding.value;
                    },
                    // 指令所在元素被插入页面时
                    inserted(element,binding){
                        console.log('fbind-inserted',this);
                        console.log('inserted');
                        element.focus();
                    },
                    // 指令所在的模板被重新解析时
                    update(element,binding){
                        console.log('fbind-update',this);
                        console.log('update');
                        element.value=binding.value;
                        // element.focus();
                    }
                } */
            }
        });

        new Vue({ 
            el:'#root2',
            data:{
                x:1
            }
        });
        
        
    </script>
</html>

3、回顾一个DOM操作

<!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>
    <style>
        .demo{
            background-color: yellow;
        }
    </style>
</head>
<body>
    <button id="btn">点我创建一个输入框</button>
    <script>
        const btn = document.getElementById('btn');
        btn.onclick=()=>{
            const input = document.createElement('input');
            // 执行不了
            // input.focus();
            input.className='demo';
            input.value =99;
            input.onclick=()=>{
                alert(1);
            };
            // 执行不了
            // input.parentElement.style.backgroundColor='skyblue';
            document.body.appendChild(input);
            input.focus();
            input.parentElement.style.backgroundColor='skyblue';
        };
    </script>
</body>
</html>

4、指令总结

<!-- 
        自定义指令总结:
            一、定义语法:
                (1)局部指令:
                    new Vue({
                        directives:{
                            指令名:配置对象
                        }               
                    });
                    或
                    new Vue({
                        directives:{
                            指令名:回调函数
                        }
                    });
                (2)全局指令:
                    Vue.directive(指令名,配置对象)或 Vue.directive(指令名,回调函数)
            二、配置对象中常用的三个回调:
                    (1)bind:指令与元素成功绑定时调用
                    (2)inserted:指令所在模板插入页面时调用
                    (3)update:指令所在模板结构被重新解析时调用
            三、备注:
                    1、指令定义时不加v-,但在使用时需要加v-
                    2、指令名如果是多个单词,需要使用kebab-case命名方式,不要用camelCase命名
     -->

19、生命周期

1、引出生命周期

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        生命周期:
            1、又名:生命周期回调函数、生命周期函数、生命周期钩子
            2、是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数
            3、生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的
            4、生命周期函数中的this指向是vm或组件实例对象
     -->
    <div id="root">
        <h2 :style="{opacity}">欢迎学习Vue</h2>

    </div>
</body>
    <script>
        const vm = new Vue({ 
            el:'#root',
            data:{
                opacity:1,
            },
            methods: {
                
            },
            // Vue完成模板的解析并把初始的真实的DOM元素放入页面后(挂载完毕)调用mounted
            mounted() {
                setInterval(()=>{
                    this.opacity-=0.01;
                    if(this.opacity<=0){
                        this.opacity=1;
                    }
                },16);
            },
        });

        // 通过外部的定时器实现(不推荐)
        /* setInterval(()=>{
            vm.opacity-=0.01;
            if(vm.opacity<=0){
                vm.opacity=1;
            }
        },16); */
        
    </script>
</html>

2、分析生命周期

<!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="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        <h2 v-text="n"></h2>
        <h2>当前的n值是:{{n}}</h2>
        <button @click="add">点我n+1</button>
        <button @click="bye">点我销毁vm</button>
    </div>
</body>
    <script>
        new Vue({ 
            el:'#root',
            /* template:`
            <div>
                <h2>当前的n值是:{{n}}</h2>
                <button @click="add">点我n+1</button>
            </div>
            `, */
            data:{
                n:1,
            },
            methods: {
                add(){
                    console.log('add');
                    this.n++;
                },
                bye(){
                    console.log('bye');
                    this.$destroy();
                }
            },
            watch:{
                n(){
                    console.log("n变了");
                }
            },
            beforeCreate() {
                // 数据代理还未开始
                console.log('beforeCreate');
                console.log(this);
                // debugger;
            },
            created() {
                console.log('created');
                // console.log(this);
                // debugger;
            },
            beforeMount() {
                console.log('beforeMount');
                // console.log(this);
                // debugger;
            },
            mounted() {
                console.log('mounted');
                // console.log(this);
                // debugger;
            },
            beforeUpdate() {
                console.log('beforeUpdate');
                // 数据更新了,页面还未更新
                console.log(this.n);
                // debugger;
            },
            updated() {
                console.log('updated');
                // 数据更新了,页面还未更新
                console.log(this.n);
                // debugger;
            },
            beforeDestroy() {
                console.log('beforeDestroy');
                this.add();
            },
            destroyed() {
                // 没什么用
                console.log('destroyed');
                console.log(this.n);
            },
        });
        
    </script>
</html>

image-20221106201017872

生命周期

3、生命周期总结

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        常用的生命周期钩子:
            1、mounted:发送ajax请求、启动定时器、绑定自定义事件、订阅信息等(初始化操作)
            2、beforeDestory:清除定时器、解绑自定义事件、取消订阅消息等(收尾工作)

        关于销毁Vue实例:
            1、销毁后借助Vue开发者工具看不到任何信息
            2、销毁后自定义事件会失效、但原生DOM事件依然有效
            3、一般不会在beforeDestory操作数据,因为即使操作了数据,也不会再触发更新流程了
     -->
    <div id="root">
        <h2 :style="{opacity}">欢迎学习Vue</h2>
        <button @click="opacity=1">透明度设置为1</button>
        <button @click="stop">点我停止变化</button>
    </div>
</body>
    <script>
        const vm = new Vue({ 
            el:'#root',
            data:{
                opacity:1,
            },
            methods: {
                stop(){
                    // clearInterval(this.timer);
                    vm.$destroy();
                }
            },
            // Vue完成模板的解析并把初始的真实的DOM元素放入页面后(挂载完毕)调用mounted
            mounted() {
                this.timer = setInterval(()=>{
                    this.opacity-=0.01;
                    if(this.opacity<=0){
                        this.opacity=1;
                    }
                },16);
            },
            beforeDestroy() {
                clearInterval(this.timer);
                console.log("vm已经结束了");
            },
        });

        // 通过外部的定时器实现(不推荐)
        /* setInterval(()=>{
            vm.opacity-=0.01;
            if(vm.opacity<=0){
                vm.opacity=1;
            }
        },16); */
        
    </script>
</html>

20、Vue组件化编程

image-20221106215457363

image-20221106215417639

image-20221106215650758

模块:

1、理解:向外提供特定功能的js程序,一般就是一个js文件

2、为什么:js文件很多很复杂

3、作用:复用js、简化js的编写、提高js运行效率

组件:

1、理解:用来实现局部(特定)功能效果的代码集合(html/css/js/image/...)

2、为什么:一个界面的功能很复杂

3、作用:复用编码、简化项目编码、提高运行效率

模块化:

当应用中的js都以模块来编写的,那么这个应用就是一个模块化应用

组件化:

当应用中的功能都是多组件的方式来编写的,那这个应用就是一个组件化的应用

21、非单文件组件

一个文件中包含有n个组件

1、基本使用

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        Vue中使用组件的三大步骤:
            一、定义组件(创建组件)
            二、注册组件
            三、使用组件(写组件标签)
        一、如何定义一个组件?
            使用Vue.extend(options)创建,其中options和new Vue(options)是传入的那个options几乎一模一样,但是
            区别如下:
                1、el不要写,为什么?——最终所有的组件都要经过一个vm的管理,由vm中的el决定服务于哪个容器
                2、data必须写成函数,为什么?——避免组件被复用是,数据存在引用关系
            备注:使用template可以配置组件结构
     -->
    <div id="root">
        <h1>{{msg}}</h1>
        <hr>
        <!-- 3、使用school组件 -->
        <school></school>
        <!-- <h2>学校名称:{{schoolName}}</h2>
        <h2>学校地址:{{address}}</h2> -->
        <hr>
        <!-- 3、使用student组件 -->
        <student></student>
        <!-- <student></student> -->
        <!-- <h2>学生姓名:{{studentName}}</h2>
        <h2>学生年龄:{{age}}</h2> -->
        <hello></hello>
    </div>

    <hr>
    <div id="root2">
        <!-- <student></student> -->
        <hello></hello>
    </div>

</body>
    <script>

        // 1、创建school组件
        const school = Vue.extend({
            // el:'#root',//组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器
            template:`
            <div>
                <h2>学校名称:{{schoolName}}</h2>
                <h2>学校地址:{{address}}</h2>
                <button @click='showName'>点我提示学校名</button>
            </div>
            `,
            data(){
                return{
                    schoolName:'广东财经大学',
                    address:'广州',
                }
            },
            methods: {
                showName(){
                    alert(this.schoolName);
                }
            },
        });
        
        // 1、创建student组件
        const student = Vue.extend({
            // el:'#root',//组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器
            template:`
            <div>
                <h2>学生姓名:{{studentName}}</h2>
                <h2>学生年龄:{{age}}</h2>
            </div>
            `,
            data(){
                return{
                    studentName:'小林',
                    age:18,
                }
            }
        });

        // 1、创建hello组件
        const hello = Vue.extend({
            template:`
                <div>
                    <h2>{{msg}}Vue!</h2>
                </div>
                `,
            data(){
                return{
                    msg:'你好'
                }
            }
        });

        // 2、注册组件(全局注册)
        Vue.component('hello',hello);
    

        // 创建vm
        new Vue({ 
            el:'#root',

            /* data:{
                schoolName:'广东财经大学',
                address:'广州',
                studentName:'小林',
                age:18,
            } */

            data:{
                msg:'你好!',
            },
            // 2、注册组件(局部注册)
            components:{
                /* school:school,
                student:student, */
                school,
                student,
            }
        });
        


        new Vue({ 
            el:'#root2',
            components:{
                student,
            }
        });
        


    </script>
</html>

2、几个注意点

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        几个注意点:
            1、关于组件名:
                一个单词组成:
                    第一种写法(首字母小写):school
                    第二种写法(首字母大写);School
                多个单词组成:
                    第一种写法(kebab-case命名):my-school
                    第二种写法(CamelCase命名):MySchool(需要Vue脚手架支持)
                备注:
                    (1)组件名尽可能回避Html中已有的元素名称,例如:h2、H2都不行
                    (2)可以使用name配置项指定组件在vue开发者工具中显示的名字
                
            2、关于组件标签:
                第一种写法:<school></school>
                第二种写法:<school/>
                备注:不用使用脚手架时,<school/>会导致后续组件不能渲染
            
            3、一个简写方法:
                const school = Vue.extend(options) 可简写为:const school = options
     -->
    <div id="root">
        <h2>{{msg}}</h2>
        <school></school>
        <!-- <my-school></my-school> -->
        <!-- <my-school/>
        <my-school/>
        <my-school/> -->
        <!-- <MySchool></MySchool> -->
    </div>
</body>
    <script>

        /* const s = Vue.extend({
            name:'gdufe',
            template:`
            <div>
                <h2>学校名称:{{schoolName}}</h2>
                <h2>学校地址:{{address}}</h2>
            </div>
            `,
            data(){
                return{
                    schoolName:'广东财经大学',
                    address:'广州',
                }
            }
        }); */


        const s ={
            name:'gdufe',
            template:`
            <div>
                <h2>学校名称:{{schoolName}}</h2>
                <h2>学校地址:{{address}}</h2>
            </div>
            `,
            data(){
                return{
                    schoolName:'广东财经大学',
                    address:'广州',
                }
            }
        };




        new Vue({ 
            el:'#root',
            data:{
                msg:'欢迎来学习Vue!',
            },
            components:{
                school:s,
                // 'my-school':s,
                // MySchool:s,
            }
        });
        
    </script>
</html>

3、组件的嵌套

<!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="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        <!-- <hello></hello>
        <school></school> -->
        <!-- <app></app> -->
    </div>
</body>
    <script>

         // 定义student组件
         const student =Vue.extend({
            template:`
            <div>
                <h2>学生名称:{{name}}</h2>
                <h2>学生年龄:{{age}}</h2>
            </div>
            `,
            data(){
                return{
                    name:'小林',
                    age:18,
                }
            }
        });


        // 定义school组件
        const school =Vue.extend({
            name:'gdufe',
            template:`
            <div>
                <h2>学校名称:{{name}}</h2>
                <h2>学校地址:{{address}}</h2>
                <student></student>
            </div>
            `,
            data(){
                return{
                    name:'广东财经大学',
                    address:'广州',
                }
            },
            // 注册组件(局部)
            components:{
                student,
            }
        });


        // 定义hello组件
        const hello = Vue.extend({
            template:`
                <h1>{{msg}}</h1>
            `,
            data(){
                return{
                    msg:'欢迎学习Vue',
                }
            },

        });


        // 定义app组件
        const app = Vue.extend({
            template:`
                <div>
                    <hello></hello>
                    <school></school>
                </div>
            `,
            components:{
                school,
                hello
            }

        });



        // 创建vue实例
        new Vue({ 
            template:`
            <app></app>
            `,
            el:'#root',
            // 注册组件(局部注册)
            components:{
                app
            }
        });
        
    </script>
</html>

app一人之下,万人之上

4、VueComponent

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        关于:VueComponent:
            1、school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的

            2、我们只需要写<school/>或<school></school>,Vue解析时会帮我们创建school组件的实例对象
            即Vue帮我们执行的:new VueComponent(options).

            3、特别注意:每次调用Vue.extend,返回的都是一个全新的VueComponent!!!

            4、关于this指向:
                (1)组件配置中:
                    data函数、methods中的函数、watch中的函数、computed中的函数,他们的this都是【VueComponent实例对象】
                (2)new Vue(options)配置中:
                    data函数、methods中的函数、watch中的函数、computed中的函数,他们的this都是【Vue实例对象】
            5、VueComponent的实例对象,以后简称vc(也可以称为:组件实例对象)
                Vue的实例对象,以后简称vm
     -->
    <div id="root">
        <hello></hello>
        <school></school>
    </div>
</body>
    <script>
       

        // 定义school组件
        const school =Vue.extend({
            name:'gdufe',
            template:`
            <div>
                <h2>学校名称:{{name}}</h2>
                <h2>学校地址:{{address}}</h2>
                <button @click='showName'>点我提示学校名</button>
            </div>
            `,
            data(){
                return{
                    name:'广东财经大学',
                    address:'广州',
                }
            },
            methods: {
                showName(){
                    console.log(this);
                    alert(this.name);
                }
            },
        });

        // 定义test组件
         const test = Vue.extend({
            template:`
                <span>{{test}}</span>
            `,
            data(){
                return{
                    test:'This is a test',
                }
            },

        });


         // 定义hello组件
         const hello = Vue.extend({
            template:`
            <div>
                <h1>{{msg}}</h1>
                <test></test>
            </div>
            `,
            data(){
                return{
                    msg:'欢迎学习Vue',
                }
            },
            components:{
                test,
            }

        });
         

        // console.log(school);
        // console.log(hello);
        // console.log(school===hello);

        // 创建vue实例
        const vm = new Vue({ 
            el:'#root',
            // 注册组件(局部注册)
            components:{
                school,
                hello,
            }
        });

        console.log(vm);
        
    </script>
</html>

5、一个重要的内置关系

<!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="../js/vue.js"></script>
</head>
<body>
    <!-- 
        1、一个重要的内置关系:VueComponent.prototype.__proto__==Vue.prototype
        2、为什么要有这个关系:让组件实例对象(vc)可以1访问到Vue原型上的属性、方法。
     -->
    <div id="root">
        school
    </div>
</body>
    <script>

        Vue.prototype.x=99;

        // 定义school组件
        const school =Vue.extend({
            name:'gdufe',
            template:`
            <div>
                <h2>学校名称:{{name}}</h2>
                <h2>学校地址:{{address}}</h2>
                <button @click="showX">点我输出x</button>
            </div>
            `,
            data(){
                return{
                    name:'广东财经大学',
                    address:'广州',
                }
            },
            methods: {
                showX(){
                    console.log(this.x);
                }
            },
        });

        // 创建一个vm
        new Vue({ 
            el:'#root',
            data:{
                msg:'hello'
            },
            components:{
                school,
            }
        });
        
        // console.log(school.prototype.__proto__===Vue.prototype);//true






        // 定义一个构造函数
        /* function Demo(){
            this.a=1;
            this.b=2;
        }
        // 创建一个Demo实例对象
        const d = new Demo();

        console.log(Demo.prototype);//显示原型属性
        console.log(d.__proto__);//隐式原型属性

        // 通过显示原型属性操作原型对象,追加一个x属性,值为99
        Demo.prototype.x = 99;

        // console.log(d.__proto__.x);
        console.log(d.x); */


    </script>
</html>

image-20221107085319418

22、单文件组件

一个文件中只包含有一个组件

School.vue

<template>
    <!-- 组件的结构 -->
    <div class="demo">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
        <button @click="showName">点我输出学校名</button>
    </div>
</template>



<script>
    // 组件交互相关的代码(数据、方法等等)
    export default {
        name:'School',
        data(){
            return{
                name:'广东财经大学',
                address:'广州',
            }
        },
        methods: {
            showName(){
                console.log(this.name);
            }
        },
    };
    // export {school}
    // export default school;
</script>


<style>
    /* 组件的样式 */
    .demo{
        background-color:orange;
    }
</style>

Student.vue

<template>
    <!-- 组件的结构 -->
    <div>
        <h2>学生姓名:{{name}}</h2>
        <h2>学生年龄:{{age}}</h2>
    </div>
</template>



<script>
    // 组件交互相关的代码(数据、方法等等)
    export default {
        name:'Student',
        data(){
            return{
                name:'小林',
                age:21,
            }
        }
    };
</script>



App.vue

<template>
    <div>
        <School></School>
        <Student></Student>
    </div>
</template>

<script>
    // 引入组件
    import SchoolVue from './School.vue';
    import StudentVue from './Student.vue';
    export default {
        name:'App',
        components:{
            School,
            Student,
        }
    }
</script>


main.js

import AppVue from './App.vue'

new Vue({
    el:("#root"),
    template:`<App></App>`,
    components:{
        App,
    },
});

index.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>练习一下单文件组件的语法</title>

</head>
<body>
    <div id="root">
        <!-- <App></App> -->
    </div>
    <!-- <script src="../js/vue.js"></script>
    <script src="./main.js"></script> -->
</body>
</html>

以上代码还不能直接执行,需要在脚手架中才可以!!!

23、Vue脚手架

1、Vue脚手架是Vue官方提供的标准化开发工具(开发平台)

2、最新版本是4.x

3、文档:cli.vuejs.org/zh/

1、操作步骤

配置 npm 淘宝镜像:npm config set registry registry.npm.taobao.org

1、全局安装@vue/cli
npm install -g @vue/cli
2、切换到要创建项目的目录,创建项目
vue create xxxx
3、启动项目
npm run serve

高版本启动报错---name

组件名需要多个单词,且使用驼峰写法

image-20221107170547094

2、脚手架项目

main.js


/* 
    该文件是整个项目的入口文件
*/
// 引入Vue
// import Vue from "vue/dist/vue";
import Vue from "vue";
// 引入App组件,它是所有组件的父组件
import App from './App.vue'

// 关闭vue的生产提示
Vue.config.productionTip=false




/* 
    关于不同版本的Vue:
    1、vue.js与vue.runtime.xxx.js的区别
        (1)vue.js是完整版的vue,包含:核心功能+模板解析器
        (2)vue.runtime.xxx.js是运行版的Vue,只包含:核心功能,没有模板解析器
    2、因为vue.runtime.xxx.js没有模板解析器,所以不能使用template配置项,需要使用
    render函数接收到的createElement函数去指定具体内容
*/
// 创建vue实例对象--vm
new Vue({
    el:("#app"),
    // 将App组件放入容器中
    render:h=>h(App),
    // render:createElement=>createElement('h1','你好啊')
    /* template:`<App></App>`,
    components:{
        App,
    }, */
});

其他与上面代码一致

3、修改脚手架默认配置

Vue 脚手架隐藏了所有 webpack 相关的配置,若想查看具体的 webpakc 配置, 请执行:vue inspect > output.js

修改默认配置:vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true
})
/* module.exports = {
    pages: {
      index: {
        // page 的入口
        entry: 'src/index/main.js',
        // 模板来源
        template: 'public/index.html',
        // 在 dist/index.html 的输出
        filename: 'index.html',
        // 当使用 title 选项时,
        // template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
        title: 'Index Page',
        // 在这个页面中包含的块,默认情况下会包含
        // 提取出来的通用 chunk 和 vendor chunk。
        chunks: ['chunk-vendors', 'chunk-common', 'index']
      },

    },
    linOnSave:false//关闭语法检查
  } */

4、脚手架文件结构

├── node_modules 
├── public
   ├── favicon.ico: 页签图标
   └── index.html: 主页面
├── src
   ├── assets: 存放静态资源
      └── logo.png
   │── component: 存放组件
      └── HelloWorld.vue
   │── App.vue: 汇总所有组件
   │── main.js: 入口文件
├── .gitignore: git版本管制忽略的配置
├── babel.config.js: babel的配置文件
├── package.json: 应用包配置文件 
├── README.md: 应用描述文件
├── package-lock.json:包版本控制文件

关于不同版本的Vue:

1、vue.js与vue.runtime.xxx.js的区别
        (1)vue.js是完整版的vue,包含:核心功能+模板解析器
        (2)vue.runtime.xxx.js是运行版的Vue,只包含:核心功能,没有模板解析2、因为vue.runtime.xxx.js没有模板解析器,所以不能使用template配置项,需要使用
    render函数接收到的createElement函数去指定具体内容

vue.config.js配置文件

使用vue inspect > output.js 可以查看Vue脚手架的默认配置

使用vue.config.js 可以对脚手架进行个性化定制,详情见:https://cli.vuejs.org/zh

24、ref属性

1、被用来给元素或子组件注册引用信息(id的替换者)

2、应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)

3、使用方式:
		打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
		获取:this.$refs.xxx

源代码

School.vue

<template>
    <div class="school">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
    </div>
</template>

<script>
export default {
    name:'SchoolS',
    data() {
        return {
            name:'尚硅谷',
            address:'北京',
        }
    },
}
</script>

<style>
    .school{
        background-color: yellow;
    }
</style>

App.vue

<template>
    <div>
        <h1 v-text='msg' ref="title"></h1>
        <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button>
        <School ref="sch"/>
    </div>
</template>

<script>
    import School from './components/School'
    export default {
        name:'App',
        components:{School},
        data() {
            return {
                msg:'欢迎学习Vue!'
            }
        },
        methods:{
            showDOM(){
                console.log(this.$refs.title);//真实DOM元素
                console.log(this.$refs.btn);//真实DOM元素
                console.log(this.$refs.sch);//School组件的实例对象vc
            }
        }
    }
</script>

<style>

</style>

main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';
// 关闭生产提示
Vue.config.productionTip=false;
// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
});


25、props配置项

配置项props

功能:让组件接收外部传过来的数据
(1)传递数据:
	<Demo name='xxx'/>
(2)接收数据:
	第一种方式(只接收):
	props:['name']
	第二种方式(限制类型):
	props:{
		name:Number
	}
	第三种方式(限制类型、限制必要性、指定默认值)
	props:{
		name:{
			type:String,//类型
			required:true,//必要性
			default:'老王'//默认值
		}
	}
备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。

源代码

student.vue

<template>
    <div>
        <h1>{{msg}}</h1>
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <h2>学生年龄:{{myAge+1}}</h2>
        <button @click="updateAge">尝试修改收到的年龄</button>
    </div>
</template>

<script>
export default {
    name:'StudentS',
    data() {
        return {
            msg:'我是一个学生',
            // name:'小林',
            // sex:'男',
            // age:21
            myAge:this.age,
        }
    },
    methods:{
        updateAge(){
            this.myAge ++;
        }
    },
    props:['name','sex','age'],//简单声明接收

    //接收的同时对数据类型限制
    /* props:{
        name:String,
        age:Number,
        sex:String,
    } */

    // 接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
    /* props:{
        name:{
            type:String,//name的类型是字符串的
            required:true,//name是必要的
        },
        age:{
            type:Number,
            default:1 // 默认值
        },
        sex:{
            type:String,
            required:true,
        }
    } */
}
</script>

App.vue

<template>
    <div>
        <!-- <Student name='李四' sex='男' :age='18'/> -->
        <!-- <Student name='李四' sex='男' :age='18'/> -->
        <Student name='李四' sex='男' :age='18'/>
        <!-- <Student name='小红' sex='女' age='20'/> -->
    </div>
</template>

<script>
    import Student from './components/Student'
    export default {
        name:'App',
        components:{Student},
    }
</script>

<style>

</style>

main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';
// 关闭生产提示
Vue.config.productionTip=false;
// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
});


26、minxin混入

功能:可以把多个组件共用的配置提取成一个混入对象
使用方式:
	第一步(新建一个js文件)定义混合,例如:
		{
			data(){...},
			methods:{...},
			...
		}
	第二步使用混入,例如:
		(1)全局混入:在main.js中:Vue.mixin(xxx)
		(2)局部混入:在vc中配置项:mixins:['xxx']

源代码

School.vue

<template>
    <div>
        <h1>{{msg}}</h1>
        <h2 @click="showName">学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
    </div>
</template>

<script>
// 引入一个mixin
import {mixin} from '../mixin'

export default {
    name:'SchoolS',
    data() {
        return {
            msg:'我是一个学生',
            name:'尚硅谷',
            address:'北京',
        }
    },
    mixins:[mixin]
}
</script>

Student.vue

<template>
    <div>
        <h1>{{msg}}</h1>
        <h2 @click="showName">学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
    </div>
</template>

<script>
import {mixin,mixin2} from '../mixin'
export default {
    name:'StudentS',
    data() {
        return {
            msg:'我是一个学生',
            name:'小林',
            sex:'男',
        }
    },
    mixins:[mixin,mixin2],
}
</script>

App.vue

<template>
    <div>
        <School/>
        <hr>
        <Student/>
    </div>
</template>

<script>
    import School from './components/School';
    import Student from './components/Student'
    export default {
        name:'App',
        components:{Student,School},
    }
</script>

<style>

</style>

main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';

// import {mixin,mixin2} from './mixin'

// 关闭生产提示
Vue.config.productionTip=false;
// Vue.mixin(mixin);
// Vue.mixin(mixin2);
// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
});


mixin.js

export const mixin = {
    methods:{
        showName(){
            alert(this.name);
        }
    }
}
export const mixin2 = {
    data(){
        return{
            x:99,
        }
    }
}


27、插件

功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据
定义插件:
	对象.install = function(Vue,options){
		//1、添加全局过滤器
		Vue.filter(...)
		//2、添加全局指令
		Vue.directive(...)
		//3、配置全局混入
		Vue.mixin(...)
		//4、添加实例方法
		Vue.prototype.$myMethod = function(){...}
		Vue.prototype.$myProperty = xxx
	}
使用插件:Vue.use()

源代码

school.vue

<template>
    <div>
        <h2>学校名称:{{name | mySlice}}</h2>
        <h2>学校地址:{{address}}</h2>
        <button @click="test">点我测试一下hello</button>
    </div>
</template>

<script>

export default {
    name:'SchoolS',
    data() {
        return {
            name:'尚硅谷66666',
            address:'北京',
        }
    },
    methods:{
        test(){
            this.hello();
        }
    }
}
</script>

Student.vue

<template>
    <div>
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <input type="text" v-fbind:value="name">
    </div>
</template>

<script>
export default {
    name:'StudentS',
    data() {
        return {
            name:'小林',
            sex:'男',
        }
    }
}
</script>

App.vue

<template>
    <div>
        <School/>
        <hr>
        <Student/>
    </div>
</template>

<script>
    import School from './components/School';
    import Student from './components/Student'
    export default {
        name:'App',
        components:{Student,School},
    }
</script>

<style>

</style>

main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';

// 引入插件
import plugins  from './plugins';
// 关闭生产提示
Vue.config.productionTip=false;

// 应用(使用)插件
Vue.use(plugins);

// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
});


plugins.js

export default {
    install(Vue){
        // console.log('install',Vue);
        // 全局过滤器
        Vue.filter('mySlice',function(value){
            return value.slice(0,4);
        });
        // 自定义全局指令
        Vue.directive('fbind',{
            bind(element,binding){
                element.value=binding.value;
            },
            inserted(element){
                element.focus();
            },
            update(element,binding){
                element.value=binding.value;
            }
        });


        // 定义混入
        Vue.mixin({
            data(){
                return{
                    x:100,
                    y:200,
                }
            },
        });

        // 给Vue原型上添加一个方法(vm和vc都能用)
        Vue.prototype.hello= ()=>{
            alert("你好");
        };

    }
}

28、scoped样式

scoped样式:
	作用:让样式在局部生效,防止冲突
	写法:<style scoped></style>

源代码

School.vue

<template>
    <div class="demo">
        <h2 class="title">学校名称:{{name}}</h2>
        <h2 class="qwe">学校地址:{{address}}</h2>
    </div>
</template>

<script>

export default {
    name:'SchoolS',
    data() {
        return {
            name:'尚硅谷66666',
            address:'北京',
        }
    },
}
</script>

<!-- <style scoped>
    .demo{
        background-color: skyblue;
    }
</style> -->

<!-- 需要先安装less解析器 npm i less-loader -->
<style lang="less" scoped>
    .demo{
        background-color: skyblue;
        .qwe{
            font-size: 40px;
        }
    }
</style>

Student.vue

<template>
    <div class="demo">
        <h2 class="title">学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
    </div>
</template>

<script>
export default {
    name:'StudentS',
    data() {
        return {
            name:'小林',
            sex:'男',
        }
    }
}
</script>

<style scoped>
    .demo{
        background-color: orange;
    }
</style>

App.vue

<template>
    <div>
        <h1 class="title">你好啊!</h1>
        <School/>
        <hr>
        <Student/>
    </div>
</template>

<script>
    import School from './components/School';
    import Student from './components/Student'
    export default {
        name:'App',
        components:{Student,School},
    }
</script>

<!-- <style>
    .title{
        color: red;
    }
</style> -->


main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';


// 关闭生产提示
Vue.config.productionTip=false;



// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
});


29、Todo-list案例

组件化编码流程(通用)

1、实现静态组件:抽取组件,使用组件实现静态页面效果
2、展示动态数据:
	2.1、数据的类型、名称是什么?  数组里面放对象
	2.2、数据保存在哪个组件?  List
3、交互---从绑定事件监听开始

image-20221108102924714

一开始展示的数据是放在List中的,但是Header要添加一条数据,现阶段很难实现从Header向List传送一条数据,解决方案:

1、将数据放在App.vue(父组件)
2、由App.vue将数据传送给List.vue(使用props)
3、App.vue声明一个向数组添加数据的方法,并把方法传递给Header组件,Header使用该方法向数组添加数据

源代码

MyHeader.vue

<template>
    <div class="todo-header">
        <!-- <input v-model="title" type="text" placeholder="请输入你的任务名称,按回车键确认" @keyup.enter="add"/> -->
        <input type="text" placeholder="请输入你的任务名称,按回车键确认" @keyup.enter="add"/>
    </div>
</template>

<script>
    import {nanoid} from 'nanoid'
    export default {
        name:'MyHeader',
        /* data(){
            return{
                title:'',
            }
        }, */
        props:[
            'addTodo'
        ],
        methods: {
            add(event){
                // 判断输入框是否为空
                if(!event.target.value.trim()){
                    return alert("输入不能为空!");
                }
                // 将用户的输入包装成为一个todo对象
                const todoObj = {
                    id:nanoid(),
                    title:event.target.value,
                    done:false
                }
                // 将对象交给App,让App添加对象
                this.addTodo(todoObj);
                // 清空输入框
                event.target.value='';
                // console.log(event.target.value);
            }
        },
    }
</script>

<style scoped>
     /*header*/
     .todo-header input {
        width: 560px;
        height: 28px;
        font-size: 14px;
        border: 1px solid #ccc;
        border-radius: 4px;
        padding: 4px 7px;
    }

    .todo-header input:focus {
        outline: none;
        border-color: rgba(82, 168, 236, 0.8);
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
    }
</style>

MyList.vue

<template>
    <ul class="todo-main">
        <MyItem :checkTodo='checkTodo' 
                v-for="todoObj in todos" 
                :key="todoObj.id" 
                :thing="todoObj"
                :deleteTodo="deleteTodo"
        />
    </ul>
</template>

<script>
import MyItem from './MyItem';
    export default {
        name:'MyList',
        components:{
            MyItem,
        },
        props:[
            'todos',
            'checkTodo',
            'deleteTodo'
        ]
    }
</script>

<style scoped>
    /*main*/
    .todo-main {
        margin-left: 0px;
        border: 1px solid #ddd;
        border-radius: 2px;
        padding: 0px;
    }

    .todo-empty {
        height: 40px;
        line-height: 40px;
        border: 1px solid #ddd;
        border-radius: 2px;
        padding-left: 5px;
        margin-top: 10px;
    }
</style>

MyItem.vue

<template>
    <li >
        <label>
            <input type="checkbox" :checked='thing.done' @change="handleCheck(thing.id)"/>
            <!-- 如下代码也能实现功能,但是不太推荐,违背了不能修改props的原则 -->
            <!-- <input type="checkbox" v-model="thing.done"/> -->
            <span>{{thing.title}}</span>
        </label>
        <button @click="deleteItem(thing.id,thing.title)" class="btn btn-danger">删除</button>
    </li>
</template>

<script>
    export default {
        name:'MyItem',
        props:[
            // 声明接收thing对象
            'thing',
            'checkTodo',
            'deleteTodo'
        ],
        methods:{
            // 勾选or取消勾选
            handleCheck(id){
                // console.log(id);
                // 通知App组件将对应的todo对象的done值取反
                this.checkTodo(id);
            },
            deleteItem(id,title){
                if(confirm('确定删除"'+title+'"这个任务项吗?')){
                    // console.log(id,title);
                    // 通知App删除
                    this.deleteTodo(id);
                }
            }
        }
    }
</script>

<style scoped>
    /*item*/
    li {
        list-style: none;
        height: 36px;
        line-height: 36px;
        padding: 0 5px;
        border-bottom: 1px solid #ddd;
    }

    li label {
        float: left;
        cursor: pointer;
    }

    li label li input {
        vertical-align: middle;
        margin-right: 6px;
        position: relative;
        top: -1px;
    }

    li button {
        float: right;
        display: none;
        margin-top: 3px;
    }

    li:before {
        content: initial;
    }

    li:last-child {
        border-bottom: none;
    }

    li:hover{
        background-color: yellowgreen;
    }

    li:hover button{
        display: block;
    }
</style>

MyFooter.vue

<template>
    <div class="todo-footer" v-show="total">
        <label>
        <!-- <input type="checkbox" :checked='isAll' @change='checkAll'/> -->
        <input type="checkbox" v-model="isAll"/>
        </label>
        <span>
        <span>已完成{{doneTotal}}</span> / 全部{{total}}
        </span>
        <button class="btn btn-danger" @click="clearDone">清除已完成任务</button>
    </div>
</template>
<script>
    export default {
        name:'MyFooter',
        props:[
            'todos',
            'checkAllTodo',
            'deleteDoneTodo'
        ],
        computed:{
            total(){
                return this.todos.length;
            },
            doneTotal(){
                /* let i = 0;
                this.todos.forEach((todo)=>{
                    if(todo.done){
                        i++;
                    }
                })
                return i; */
                /* const x = this.todos.reduce((pre,current)=>{
                    console.log("@",pre,current);
                    return pre+(current.done ? 1 : 0);
                },0);
                return x; */
                return this.todos.reduce((pre,current)=>pre+(current.done ? 1 : 0),0);
            },
            /* isAll(){
                return (this.doneTotal===this.total &&this.total>0);
            } */
            isAll:{
                get(){
                    return (this.doneTotal===this.total &&this.total>0);
                },
                set(value){
                    this.checkAllTodo(value);
                }
            }
        },
        methods:{
            /* checkAll(e){
                this.checkAllTodo(e.target.checked);
            } */
            clearDone(){
                this.deleteDoneTodo();
            }
        }
    }
</script>

<style scoped>
    /*footer*/
    .todo-footer {
        height: 40px;
        line-height: 40px;
        padding-left: 6px;
        margin-top: 5px;
    }

    .todo-footer label {
        display: inline-block;
        margin-right: 20px;
        cursor: pointer;
    }

    .todo-footer label input {
        position: relative;
        top: -1px;
        vertical-align: middle;
        margin-right: 5px;
    }

    .todo-footer button {
        float: right;
        margin-top: 5px;
    }
</style>

App.vue

<template>
    <div id="root">
        <div class="todo-container">
            <div class="todo-wrap">
            <MyHeader :addTodo="addTodo"></MyHeader>
            <MyList :deleteTodo="deleteTodo" :checkTodo="checkTodo" :todos="todos"></MyList>
            <MyFooter :deleteDoneTodo="deleteDoneTodo" :checkAllTodo="checkAllTodo" :todos="todos"></MyFooter>
        </div>
    </div>
</div>

</template>

<script>
    import MyHeader from './components/MyHeader';
    import MyList from './components/MyList';
    import MyFooter from './components/MyFooter';

    export default {
        name:'App',
        components:{
            MyHeader,
            MyList,
            MyFooter
        },
        data(){
            return{
                todos:[
                    {id:'001',title:'吃饭',done:true},
                    {id:'002',title:'睡觉',done:true},
                    {id:'003',title:'打代码',done:false},
                ]
            }
        },
        methods: {
            // 添加一个todo
            addTodo(todoObj){
                // console.log('我是App组件,我收到了数据:'+x);
                this.todos.unshift(todoObj);
            },
            //取消勾选一个todo
            checkTodo(id){
                this.todos.forEach((todo)=>{
                    if(todo.id===id) todo.done=!todo.done;
                })
            },
            // 删除一个todo项
            deleteTodo(id){
                this.todos = this.todos.filter(todo=>todo.id !==id);
            },
            // 全选/取消全选
            checkAllTodo(done){
                this.todos.forEach((todo)=>{
                    todo.done=done;
                });
            },
            // 删除已完成的任务(即done为true的todo)
            deleteDoneTodo(){
                // 删除
                // 遍历所有todo
                /* this.todos.forEach((todo)=>{
                    // 调用方法删除
                    if(todo.done){
                        this.deleteTodo(todo.id);
                    }
                }); */
                // 提示
                if(confirm('你确定要清除已完成的任务吗?')){
                    // 过滤掉
                    this.todos = this.todos.filter((todo)=>{
                        return !todo.done;
                    });
                }
                
            }
        },
    }
</script>

<style> 
    /*base*/
    body {
        background: #fff;
    }
    .btn {
        display: inline-block;
        padding: 4px 12px;
        margin-bottom: 0;
        font-size: 14px;
        line-height: 20px;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
        border-radius: 4px;
    }
    .btn-danger {
        color: #fff;
        background-color: #da4f49;
        border: 1px solid #bd362f;
    }
    .btn-danger:hover {
        color: #fff;
        background-color: #bd362f;
    }
    .btn:focus {
        outline: none;
    }
    .todo-container {
        width: 600px;
        margin: 0 auto;
    }
    .todo-container .todo-wrap {
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 5px;
    }
</style>


main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';


// 关闭生产提示
Vue.config.productionTip=false;



// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
});


总结

1. 组件化编码流程:

   ​	(1).拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突。

   ​	(2).实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:

   ​			1).一个组件在用:放在组件自身即可。

   ​			2). 一些组件在用:放在他们共同的父组件上(<span style="color:red">状态提升</span>)。

   ​	(3).实现交互:从绑定事件开始。

2. props适用于:

   ​	(1).父组件 ==> 子组件 通信

   ​	(2).子组件 ==> 父组件 通信(要求父先给子一个函数)

3. 使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!

4. props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做。

30、webStorage

  1. 存储内容大小一般支持5MB左右(不同浏览器可能还不一样)

  2. 浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。

  3. 相关API:

    1. xxxxxStorage.setItem('key', 'value'); 该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。

    2. xxxxxStorage.getItem('person');

          该方法接受一个键名作为参数,返回键名对应的值。
      
    3. xxxxxStorage.removeItem('key');

          该方法接受一个键名作为参数,并把该键名从存储中删除。
      
    4. xxxxxStorage.clear()

          该方法会清空存储中的所有数据。
      
  4. 备注:

    1. SessionStorage存储的内容会随着浏览器窗口关闭而消失。
    2. LocalStorage存储的内容,需要手动清除才会消失。
    3. xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。
    4. JSON.parse(null)的结果依然是null。

31、TodoList案例----本地存储版本

只需要在原来的代码上,添加监视:todos

在App.vue中添加:

watch:{
    todos:{
        deep:true,
        handler(value){
        	localStorage.setItem('todos',JSON.stringify(value));
   		}
 	}
}

修改data中todos的取值:

data(){
	return{
		todos:JSON.parse(localStorage.getItem('todos')) || []
	}
},

32、组件自定义事件

源代码

School.vue

<template>
    <div class="school">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
        <button @click="sendSchoolName">把学校名给App</button>
    </div>
</template>

<script>

export default {
    name:'SchoolS',
    props:[
        'getSchollName'
    ],
    data() {
        return {
            name:'尚硅谷',
            address:'北京',
        }
    },
    methods:{
        sendSchoolName(){
            this.getSchollName(this.name);
        }
    }
}
</script>

<!-- <style scoped>
    .demo{
        background-color: skyblue;
    }
</style> -->

<!-- 需要先安装less解析器 npm i less-loader -->
<style lang="less" scoped>
    .school{
        background-color: skyblue;
        padding: 5px;
    }
</style>

Student.vue

<template>
    <div class="student">
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <h2>当前求和为:{{number}}</h2>
        <button @click="add">点我number++</button>
        <button @click="sendStudentName">点我把学生姓名给App</button>
        <button @click="unbind">解绑xiaolin事件</button>
        <button @click="death">销毁当前Student组件的实例(vc)</button>
    </div>
</template>

<script>
export default {
    name:'StudentS',
    data() {
        return {
            name:'小林',
            sex:'男',
            number:0
        }
    },
    methods:{
        add(){
            console.log('add回调被调用了');
            this.number++;
        },
        sendStudentName(){
            // 触发Studnet组件实例身上的xiaolin事件
            this.$emit('xiaolin',this.name,1,2,3,4)
            // this.$emit('demo');
        },
        unbind(){
            this.$off('xiaolin');//解绑一个自定义事件
            // this.$off(['xiaolin','demo']);//解绑多个自定义事件
            // this.$off();//解绑所有自定义事件
        },
        death(){
            this.$destroy();//销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效了
        }
    }
}
</script>

<style scoped>
    .student{
        background-color: orange;
        padding: 5px;
        margin-top: 30px;
    }
</style>

App.vue

<template>
    <div class="app">
        <h1>{{msg}},学生姓名是:{{studentName}}</h1>
        <!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
        <School :getSchollName='getSchollName'/>
        <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用v-on,或@) -->
        <!-- <Student @xiaolin='getStudentName' @demo='m1'/> -->

        <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
        <!-- native声明使用原生的js事件click -->
        <!-- 会把Student组件最外层容器作为触发事件的元素 -->
        <Student ref='studnet' @click.native='show'/>
    </div>
</template>

<script>
    import School from './components/School';
    import Student from './components/Student'
    export default {
        name:'App',
        components:{Student,School},
        data(){
            return{
                msg:'你好啊!',
                studentName:''
            }
        },
        methods:{
            getSchollName(name){
                console.log("App收到了学校名:",name);
            },
            getStudentName(name,...params){
                console.log('App收到了学生姓名:',name,params);
                this.studentName = name;
            },
            m1(){
                console.log('demo事件被触发了');
            },
            show(){
                console.log(111);
            }
        },
        mounted(){
            // setTimeout(()=>{
            //     this.$refs.studnet.$on('xiaolin',this.getStudentName);   //绑定自定义事件
            // },3000);
            // this.$refs.studnet.$once('xiaolin',this.getStudentName);//绑定自定义事件(一次性)
            this.$refs.studnet.$on('xiaolin',this.getStudentName);
            /* this.$refs.studnet.$on('xiaolin',(name,...params)=>{
                console.log('App收到了学生姓名:',name,params);
                // console.log(this);//此处的this是Studnet组件
                this.studentName = name;
            }); */

        }
    }
</script>

<style scoped>
    .app{
        background-color: gray;
        padding: 5px;
    }
</style>


main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';


// 关闭生产提示
Vue.config.productionTip=false;



// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
    /* mounted(){
        setTimeout(()=>{
            this.$destroy();
        },3000);
    } */
});


总结

  1. 一种组件间通信的方式,适用于:子组件 ===> 父组件

  2. 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。

  3. 绑定自定义事件:

    1. 第一种方式,在父组件中:<Demo @atguigu="test"/><Demo v-on:atguigu="test"/>

    2. 第二种方式,在父组件中:

      <Demo ref="demo"/>
      ......
      mounted(){
         this.$refs.xxx.$on('atguigu',this.test)
      }
      
    3. 若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法。

  4. 触发自定义事件:this.$emit('atguigu',数据)

  5. 解绑自定义事件this.$off('atguigu')

  6. 组件上也可以绑定原生DOM事件,需要使用native修饰符。

  7. 注意:通过this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中要么用箭头函数,否则this指向会出问题!

33、ToDoList-----自定义事件

修改App组件

<template>
    <div id="root">
        <div class="todo-container">
            <div class="todo-wrap">
            	<MyHeader @addTodo="addTodo"></MyHeader>
            	<MyList :deleteTodo="deleteTodo" :checkTodo="checkTodo" :todos="todos"></MyList>
            	<MyFooter @deleteDoneTodo="deleteDoneTodo" 								@checkAllTodo="checkAllTodo" :todos="todos"></MyFooter>
        	</div>
    	</div>
	</div>	
</template>

修改MyHeader组件

methods: {
            add(event){
                // 判断输入框是否为空
                if(!event.target.value.trim()){
                    return alert("输入不能为空!");
                }
                // 将用户的输入包装成为一个todo对象
                const todoObj = {
                    id:nanoid(),
                    title:event.target.value,
                    done:false
                }

				//修改此部分
                // 将对象交给App,让App添加对象
                this.$emit('addTodo',todoObj);


                // 清空输入框
                event.target.value='';
                // console.log(event.target.value);
            }
        },

修改MyFooter组件

computed:{
            total(){
                return this.todos.length;
            },
            doneTotal(){
                return this.todos.reduce((pre,current)=>pre+(current.done ? 1 : 0),0);
            },
            isAll:{
                get(){
                    return (this.doneTotal===this.total &&this.total>0);
                },
                set(value){
                    // this.checkAllTodo(value);
                    this.$emit('checkAllTodo',value);
                }
            }
        },
        methods:{
            clearDone(){
                // this.deleteDoneTodo();
                this.$emit('deleteDoneTodo');
            }
        }

另外删除props中没用的值的引入

34、全局事件总线--实现任意组件间通信

源代码

SChool.vue

<template>
    <div class="school">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
    </div>
</template>

<script>

export default {
    name:'SchoolS',
    data() {
        return {
            name:'尚硅谷',
            address:'北京',
        }
    },
    mounted(){
        // console.log('School',window.x);
        // console.log('School',this.x);
        this.$bus.$on('hello',(data)=>{
            console.log('我是School组件,我收到了数据:',data);
        });
    },
    beforeDestroy(){
        this.$bus.$off('hello');
    }
}
</script>

<style lang="less" scoped>
    .school{
        background-color: skyblue;
        padding: 5px;
    }
</style>

Student.vue

<template>
    <div class="student">
        <h2>学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <button @click="sendStudentName">把学生名给School组件</button>
    </div>
</template>

<script>
export default {
    name:'StudentS',
    data() {
        return {
            name:'小林',
            sex:'男',
        }
    },
    mounted(){
        // console.log('Student',window.x);
        // console.log('Student',this.x);

    },
    methods: {
        sendStudentName(){
            this.$bus.$emit('hello',this.name);
        }
    },
}
</script>

<style scoped>
    .student{
        background-color: orange;
        padding: 5px;
        margin-top: 30px;
    }
</style>

App.vue

<template>
    <div class="app">
        <h1>{{msg}}</h1>
        <School/>
        <Student/>
    </div>
</template>

<script>
    import School from './components/School';
    import Student from './components/Student'
    export default {
        name:'App',
        components:{Student,School},
        data(){
            return{
                msg:'你好啊!'
            }
        },
    }
</script>

<style scoped>
    .app{
        background-color: gray;
        padding: 5px;
    }
</style>


main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';


// 关闭生产提示
Vue.config.productionTip=false;

// window.x=false;
// const Demo = Vue.extend({});
// const d = new Demo();
// Vue.prototype.x = d;

// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
    beforeCreate(){
        Vue.prototype.$bus = this; //安装全局事件总线
    }
});


总结

  1. 一种组件间通信的方式,适用于任意组件间通信

  2. 安装全局事件总线:

    new Vue({
     ......
     beforeCreate() {
         Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
     },
        ......
    }) 
    
  3. 使用事件总线:

    1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.$bus.$on('xxxx',this.demo)
      }
      
    2. 提供数据:this.$bus.$emit('xxxx',数据)

  4. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。

image-20221108200506801

35、ToDoList-----全局事件总线

在ToDoList自定义事件的基础上修改

1、安装全局事件总线(main.js)

 beforeCreate(){
        Vue.prototype.$bus = this; // 安装全局事件总线
    }

2、删除App组件给MyList组件传的数据(剩下todos)

<MyList  :todos="todos"></MyList>

3、删除MyList接收的数据(剩下todos)以及不要向MyItem传送数据

1、
props:['todos']

2、
<MyItem  
        v-for="todoObj in todos" 
        :key="todoObj.id" 
        :thing="todoObj"
/>

4、删除MyItem接收的数据(剩下thing)

props:[ 'thing']

5、在App组件声明绑定事件和解绑事件逻辑

mounted(){
    this.$bus.$on('checkTodo',this.checkTodo);
    this.$bus.$on('deleteTodo',this.deleteTodo);
},
beforeDestroy(){
 	this.$bus.$off('checkTodo');
	this.$bus.$off('deleteTodo');
}

6、在MyItem中声明触发事件逻辑(即传送数据)

			// 勾选or取消勾选
            handleCheck(id){
                // console.log(id);
                // 通知App组件将对应的todo对象的done值取反
                // this.checkTodo(id);
                this.$bus.$emit('checkTodo',id);
            },
            deleteItem(id,title){
                if(confirm('确定删除"'+title+'"这个任务项吗?')){
                    // console.log(id,title);
                    // 通知App删除
                    // this.deleteTodo(id);
                    this.$bus.$emit('deleteTodo',id);
                }
            }

36、消息订阅与发布

  1. 一种组件间通信的方式,适用于任意组件间通信

  2. 使用步骤:

    1. 安装pubsub:npm i pubsub-js

    2. 引入: import pubsub from 'pubsub-js'

    3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
      }
      
    4. 提供数据:pubsub.publish('xxx',数据)

    5. 最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)取消订阅。

订阅消息

methods: {
        demo(msgName,data){
            console.log("有人发布了hello消息,hello消息的回调执行了",data);
        }
    },
    mounted(){
        /* this.pubId = pubsub.subscribe('hello',(msgName,data)=>{
            console.log(this);
            console.log("有人发布了hello消息,hello消息的回调执行了",data);
        }); */

        this.pubId = pubsub.subscribe('hello',this.demo);
    },
    beforeDestroy(){
        // this.$bus.$off('hello');
        pubsub.unsubscribe(this.pubId);
    }

发布消息

methods: {
        sendStudentName(){
            // this.$bus.$emit('hello',this.name);
            pubSub.publish('hello',666);
        }
    },

37、TodoList---消息订阅与发布

在之前案例的基础上修改

1、修改App组件methods中的deleteTodo方法,参数需要改成两个,使用_占位

// 删除一个todo项
deleteTodo(_,id){
	this.todos = this.todos.filter(todo=>todo.id !==id);
},

2、修改App组件

mounted(){
    this.$bus.$on('checkTodo',this.checkTodo);
    this.pubId=pubsub.subscribe('deleteTodo',this.deleteTodo)
},
beforeDestroy(){
    this.$bus.$off('checkTodo');
    // this.$bus.$off('deleteTodo');
    pubsub.unsubscribe(this.pubId);
}

3、修改MyItem组件methods

deleteItem(id,title){
	if(confirm('确定删除"'+title+'"这个任务项吗?')){
        // console.log(id,title);
        // 通知App删除
        // this.deleteTodo(id);
        // this.$bus.$emit('deleteTodo',id);
        pubSub.publish('deleteTodo',id);
	}
}

38、TodoList--添加编辑功能

源码

MyHeader.vue

<template>
    <div class="todo-header">
        <!-- <input v-model="title" type="text" placeholder="请输入你的任务名称,按回车键确认" @keyup.enter="add"/> -->
        <input type="text" placeholder="请输入你的任务名称,按回车键确认" @keyup.enter="add"/>
    </div>
</template>

<script>
    import {nanoid} from 'nanoid'
    export default {
        name:'MyHeader',
        /* data(){
            return{
                title:'',
            }
        }, */
        methods: {
            add(event){
                // 判断输入框是否为空
                if(!event.target.value.trim()){
                    return alert("输入不能为空!");
                }
                // 将用户的输入包装成为一个todo对象
                const todoObj = {
                    id:nanoid(),
                    title:event.target.value,
                    done:false
                }
                // 将对象交给App,让App添加对象
                this.$emit('addTodo',todoObj);
                // 清空输入框
                event.target.value='';
                // console.log(event.target.value);
            }
        },
    }
</script>

<style scoped>
     /*header*/
     .todo-header input {
        width: 560px;
        height: 28px;
        font-size: 14px;
        border: 1px solid #ccc;
        border-radius: 4px;
        padding: 4px 7px;
    }

    .todo-header input:focus {
        outline: none;
        border-color: rgba(82, 168, 236, 0.8);
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
    }
</style>

MyList.vue

<template>
    <ul class="todo-main">
        <MyItem  
                v-for="todoObj in todos" 
                :key="todoObj.id" 
                :thing="todoObj"
        />
    </ul>
</template>

<script>
import MyItem from './MyItem';
    export default {
        name:'MyList',
        components:{
            MyItem,
        },
        props:[
            'todos',
        ]
    }
</script>

<style scoped>
    /*main*/
    .todo-main {
        margin-left: 0px;
        border: 1px solid #ddd;
        border-radius: 2px;
        padding: 0px;
    }

    .todo-empty {
        height: 40px;
        line-height: 40px;
        border: 1px solid #ddd;
        border-radius: 2px;
        padding-left: 5px;
        margin-top: 10px;
    }
</style>

MyItem.vue

<template>
    <li >
        <label>
            <input type="checkbox" :checked='thing.done' @change="handleCheck(thing.id)"/>
            <!-- 如下代码也能实现功能,但是不太推荐,违背了不能修改props的原则 -->
            <!-- <input type="checkbox" v-model="thing.done"/> -->
            <span v-show="!thing.isEdit">{{thing.title}}</span>
            <input
                type="text"
                v-show="thing.isEdit" 
                :value="thing.title" 
                @blur="handleBlur(thing,$event)"
                ref="inputTitle"
            >
        </label>
        <button @click="deleteItem(thing.id,thing.title)" class="btn btn-danger">删除</button>
        <button v-show="!thing.isEdit" @click="handleEdit(thing)" class="btn btn-edit">编辑</button>
    </li>
</template>

<script>
    import pubSub from 'pubsub-js'
import func from 'vue-editor-bridge';
    export default {
        name:'MyItem',
        props:[
            // 声明接收thing对象
            'thing',
        ],
        methods:{
            // 勾选or取消勾选
            handleCheck(id){
                // console.log(id);
                // 通知App组件将对应的todo对象的done值取反
                // this.checkTodo(id);
                this.$bus.$emit('checkTodo',id);
            },
            deleteItem(id,title){
                if(confirm('确定删除"'+title+'"这个任务项吗?')){
                    // console.log(id,title);
                    // 通知App删除
                    // this.deleteTodo(id);
                    // this.$bus.$emit('deleteTodo',id);
                    pubSub.publish('deleteTodo',id);
                }
            },
            // 编辑功能
            handleEdit(thing){
                if(Object.prototype.hasOwnProperty.call(thing, 'isEdit')){
                    console.log('有');
                    thing.isEdit=true;
                }else{
                    console.log('无');
                    this.$set(thing,'isEdit',true);
                }
                /* setTimeout(()=>{
                    this.$refs.inputTitle.focus();
                },200) ; */

                // 页面重新解析完毕再执行这个函数
                this.$nextTick(function(){
                    this.$refs.inputTitle.focus();
                });
            },
            // 失去焦点回调,实现修改数据的地方
            handleBlur(thing,e){
                thing.isEdit=false;
                if(!e.target.value.trim()){
                    return alert('输入不能为空!');
                }
                this.$bus.$emit('updateTodo',thing.id,e.target.value);
            }
        }
    }
</script>

<style scoped>
    /*item*/
    li {
        list-style: none;
        height: 36px;
        line-height: 36px;
        padding: 0 5px;
        border-bottom: 1px solid #ddd;
    }

    li label {
        float: left;
        cursor: pointer;
    }

    li label li input {
        vertical-align: middle;
        margin-right: 6px;
        position: relative;
        top: -1px;
    }

    li button {
        float: right;
        display: none;
        margin-top: 3px;
    }

    li:before {
        content: initial;
    }

    li:last-child {
        border-bottom: none;
    }

    li:hover{
        background-color: yellowgreen;
    }

    li:hover button{
        display: block;
    }
</style>

MyFooter.vue

<template>
    <div class="todo-footer" v-show="total">
        <label>
        <!-- <input type="checkbox" :checked='isAll' @change='checkAll'/> -->
        <input type="checkbox" v-model="isAll"/>
        </label>
        <span>
        <span>已完成{{doneTotal}}</span> / 全部{{total}}
        </span>
        <button class="btn btn-danger" @click="clearDone">清除已完成任务</button>
    </div>
</template>
<script>
    export default {
        name:'MyFooter',
        props:[
            'todos',
        ],
        computed:{
            total(){
                return this.todos.length;
            },
            doneTotal(){
                /* let i = 0;
                this.todos.forEach((todo)=>{
                    if(todo.done){
                        i++;
                    }
                })
                return i; */
                /* const x = this.todos.reduce((pre,current)=>{
                    console.log("@",pre,current);
                    return pre+(current.done ? 1 : 0);
                },0);
                return x; */
                return this.todos.reduce((pre,current)=>pre+(current.done ? 1 : 0),0);
            },
            /* isAll(){
                return (this.doneTotal===this.total &&this.total>0);
            } */
            isAll:{
                get(){
                    return (this.doneTotal===this.total &&this.total>0);
                },
                set(value){
                    // this.checkAllTodo(value);
                    this.$emit('checkAllTodo',value);
                }
            }
        },
        methods:{
            /* checkAll(e){
                this.checkAllTodo(e.target.checked);
            } */
            clearDone(){
                // this.deleteDoneTodo();
                this.$emit('deleteDoneTodo');
            }
        }
    }
</script>

<style scoped>
    /*footer*/
    .todo-footer {
        height: 40px;
        line-height: 40px;
        padding-left: 6px;
        margin-top: 5px;
    }

    .todo-footer label {
        display: inline-block;
        margin-right: 20px;
        cursor: pointer;
    }

    .todo-footer label input {
        position: relative;
        top: -1px;
        vertical-align: middle;
        margin-right: 5px;
    }

    .todo-footer button {
        float: right;
        margin-top: 5px;
    }
</style>

App.vue

<template>
    <div id="root">
        <div class="todo-container">
            <div class="todo-wrap">
            <MyHeader @addTodo="addTodo"></MyHeader>
            <MyList  :todos="todos"></MyList>
            <MyFooter @deleteDoneTodo="deleteDoneTodo" @checkAllTodo="checkAllTodo" :todos="todos"></MyFooter>
        </div>
    </div>
</div>

</template>

<script>
    import pubsub from 'pubsub-js';
    import MyHeader from './components/MyHeader';
    import MyList from './components/MyList';
    import MyFooter from './components/MyFooter';

    export default {
        name:'App',
        components:{
            MyHeader,
            MyList,
            MyFooter
        },
        data(){
            return{
                todos:JSON.parse(localStorage.getItem('todos')) || []
            }
        },
        methods: {
            // 添加一个todo
            addTodo(todoObj){
                // console.log('我是App组件,我收到了数据:'+x);
                this.todos.unshift(todoObj);
            },
            //取消勾选一个todo
            checkTodo(id){
                this.todos.forEach((todo)=>{
                    if(todo.id===id) todo.done=!todo.done;
                })
            },
            //更新一个todo
            updateTodo(id,title){
                this.todos.forEach((todo)=>{
                    if(todo.id===id) todo.title=title;
                })
            },
            // 删除一个todo项
            deleteTodo(_,id){
                this.todos = this.todos.filter(todo=>todo.id !==id);
            },
            // 全选/取消全选
            checkAllTodo(done){
                this.todos.forEach((todo)=>{
                    todo.done=done;
                });
            },
            // 删除已完成的任务(即done为true的todo)
            deleteDoneTodo(){
                // 删除
                // 遍历所有todo
                /* this.todos.forEach((todo)=>{
                    // 调用方法删除
                    if(todo.done){
                        this.deleteTodo(todo.id);
                    }
                }); */
                // 提示
                if(confirm('你确定要清除已完成的任务吗?')){
                    // 过滤掉
                    this.todos = this.todos.filter((todo)=>{
                        return !todo.done;
                    });
                }
                
            }
        },
        watch:{
            todos:{
                deep:true,
                handler(value){
                    localStorage.setItem('todos',JSON.stringify(value));
                }
            }
        },
        mounted(){
            this.$bus.$on('checkTodo',this.checkTodo);
            this.$bus.$on('updateTodo',this.updateTodo);
            this.pubId=pubsub.subscribe('deleteTodo',this.deleteTodo)
        },
        beforeDestroy(){
            this.$bus.$off('checkTodo');
            this.$bus.$off('updateTodo');
            // this.$bus.$off('deleteTodo');
            pubsub.unsubscribe(this.pubId);
        }
    }
</script>

<style> 
    /*base*/
    body {
        background: #fff;
    }
    .btn {
        display: inline-block;
        padding: 4px 12px;
        margin-bottom: 0;
        font-size: 14px;
        line-height: 20px;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
        border-radius: 4px;
    }
    .btn-danger {
        color: #fff;
        background-color: #da4f49;
        border: 1px solid #bd362f;
    }
    .btn-edit {
        color: #fff;
        background-color: skyblue;
        border: 1px solid rgb(70, 158, 193);
        margin-right: 5px;
    }
    .btn-danger:hover {
        color: #fff;
        background-color: #bd362f;
    }
    .btn-edit:hover {
        color: #fff;
        background-color: rgb(70, 158, 193);
    }
    .btn:focus {
        outline: none;
    }
    .todo-container {
        width: 600px;
        margin: 0 auto;
    }
    .todo-container .todo-wrap {
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 5px;
    }
</style>


main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';


// 关闭生产提示
Vue.config.productionTip=false;



// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
    beforeCreate(){
        Vue.prototype.$bus = this; // 安装全局事件总线
    }
});



nextTick

1. 语法:```this.$nextTick(回调函数)```
2. 作用:在下一次 DOM 更新结束后执行其指定的回调。
3. 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。

39、Vue中的过渡和动画效果

  1. 作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。

  2. 图示:

    image-20221109095811509

  3. 写法:

    1. 准备好样式:

      • 元素进入的样式:
        1. v-enter:进入的起点
        2. v-enter-active:进入过程中
        3. v-enter-to:进入的终点
      • 元素离开的样式:
        1. v-leave:离开的起点
        2. v-leave-active:离开过程中
        3. v-leave-to:离开的终点
    2. 使用<transition>包裹要过度的元素,并配置name属性:

      <transition name="hello">
        <h1 v-show="isShow">你好啊!</h1>
      </transition>
      
    3. 备注:若有多个元素需要过度,则需要使用:<transition-group>,且每个元素都要指定key值。

源码

test.vue

<template>
    <div>
        <button @click="isShow=!isShow">显示/隐藏</button>
        <transition name="hello" appear>
            <h1 v-show="isShow">你好啊</h1>
        </transition> 
    </div>
</template>

<script>
export default {
    name:'TestS',
    data(){
        return {
            isShow:true
        }
    },
}
</script>

<style scoped>
    h1{
        background-color: orange;
    }

    .hello-enter-active{
        animation: xiaolin 1s;
    }
    .hello-leave-active{
        animation: xiaolin 1s reverse;
    }

    @keyframes xiaolin {
        from{
            transform: translateX(-100%);
        }
        to{
            transform: translateX(0px);
        }
    }
</style>

test2.vue

<template>
    <div>
        <button @click="isShow=!isShow">显示/隐藏</button>
        <!-- <transition name="hello" appear>
            <h1 v-show="isShow">你好啊</h1>
        </transition> --> 
        <transition-group name="hello" appear>
            <h1 v-show="!isShow" key="1">你好啊</h1>
            <h1 v-show="isShow" key="2">尚硅谷</h1>
        </transition-group> 
    </div>
</template>

<script>
export default {
    name:'TestS',
    data(){
        return {
            isShow:true
        }
    },
}
</script>

<style scoped>
    h1{
        background-color: orange;
    }

    /* 进入的起点  离开的终点*/
    .hello-enter,.hello-leave-to{
        transform: translateX(-100%);
    }
    .hello-enter-active,.hello-leave-active{
        transition: 0.5s linear;
    }
    /* 进入的终点 离开的起点*/
    .hello-enter-to,.hello-leave{
        transform: translateX(0);
    }
    
</style>

test3.vue

<template>
    <div>
        <button @click="isShow=!isShow">显示/隐藏</button>
        <!-- <transition name="hello" appear>
            <h1 v-show="isShow">你好啊</h1>
        </transition> --> 
        <transition-group 
            appear
            name="animate__animated animate__bounce"
            enter-active-class="animate__swing"
            leave-active-class="animate__backOutUp"
        >
            <h1 v-show="!isShow" key="1">你好啊</h1>
            <h1 v-show="isShow" key="2">尚硅谷</h1>
        </transition-group> 
    </div>
</template>

<script>
import 'animate.css'
export default {
    name:'TestS',
    data(){
        return {
            isShow:true
        }
    },
}
</script>

<style scoped>
    h1{
        background-color: orange;
    }

</style>

App.vue

<template>
    <div>
        <Test></Test>
        <hr>
        <Test2></Test2>
        <hr>
        <Test3></Test3>
    </div>
</template>

<script>
    import Test from './components/test';
    import Test2 from './components/test2';
    import Test3 from './components/test3';

    export default {
        name:'App',
        components:{
            Test,
            Test2,
            Test3,
        }
    }
</script>

main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';


// 关闭生产提示
Vue.config.productionTip=false;



// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
    beforeCreate(){
        Vue.prototype.$bus = this; // 安装全局事件总线
    }
});


40、TodoList案例---动画

两种方案

1、修改MyList.vue(使用transition-group)

<template>
    <ul class="todo-main">
        <transition-group name="todo" appear>
            <MyItem  
                v-for="todoObj in todos" 
                :key="todoObj.id" 
                :thing="todoObj"
            />
        </transition-group>
    </ul>
</template>

<script>
import MyItem from './MyItem';
    export default {
        name:'MyList',
        components:{
            MyItem,
        },
        props:[
            'todos',
        ]
    }
</script>

<style scoped>
    /*main*/
    .todo-main {
        margin-left: 0px;
        border: 1px solid #ddd;
        border-radius: 2px;
        padding: 0px;
    }

    .todo-empty {
        height: 40px;
        line-height: 40px;
        border: 1px solid #ddd;
        border-radius: 2px;
        padding-left: 5px;
        margin-top: 10px;
    }

    .todo-enter-active{
        animation: xiaolin 1s;
    }
    .todo-leave-active{
        animation: xiaolin 1s reverse;
    }

    @keyframes xiaolin {
        from{
            transform: translateX(+100%);
        }
        to{
            transform: translateX(0px);
        }
    }
</style>

2、修改MyItem.vue(使用transition)

<template>
    <transition name="todo" appear>
        <li >
            <label>
                <input type="checkbox" :checked='thing.done' @change="handleCheck(thing.id)"/>
                <!-- 如下代码也能实现功能,但是不太推荐,违背了不能修改props的原则 -->
                <!-- <input type="checkbox" v-model="thing.done"/> -->
                <span v-show="!thing.isEdit">{{thing.title}}</span>
                <input
                    type="text"
                    v-show="thing.isEdit" 
                    :value="thing.title" 
                    @blur="handleBlur(thing,$event)"
                    ref="inputTitle"
                >
            </label>
            <button @click="deleteItem(thing.id,thing.title)" class="btn btn-danger">删除</button>
            <button v-show="!thing.isEdit" @click="handleEdit(thing)" class="btn btn-edit">编辑</button>
        </li>
    </transition>
</template>

<script>
    import pubSub from 'pubsub-js'
    export default {
        name:'MyItem',
        props:[
            // 声明接收thing对象
            'thing',
        ],
        methods:{
            // 勾选or取消勾选
            handleCheck(id){
                // console.log(id);
                // 通知App组件将对应的todo对象的done值取反
                // this.checkTodo(id);
                this.$bus.$emit('checkTodo',id);
            },
            deleteItem(id,title){
                if(confirm('确定删除"'+title+'"这个任务项吗?')){
                    // console.log(id,title);
                    // 通知App删除
                    // this.deleteTodo(id);
                    // this.$bus.$emit('deleteTodo',id);
                    pubSub.publish('deleteTodo',id);
                }
            },
            // 编辑功能
            handleEdit(thing){
                if(Object.prototype.hasOwnProperty.call(thing, 'isEdit')){
                    console.log('有');
                    thing.isEdit=true;
                }else{
                    console.log('无');
                    this.$set(thing,'isEdit',true);
                }
                /* setTimeout(()=>{
                    this.$refs.inputTitle.focus();
                },200) ; */

                // 页面重新解析完毕再执行这个函数
                this.$nextTick(function(){
                    this.$refs.inputTitle.focus();
                });
            },
            // 失去焦点回调,实现修改数据的地方
            handleBlur(thing,e){
                thing.isEdit=false;
                if(!e.target.value.trim()){
                    return alert('输入不能为空!');
                }
                this.$bus.$emit('updateTodo',thing.id,e.target.value);
            }
        }
    }
</script>

<style scoped>
    /*item*/
    li {
        list-style: none;
        height: 36px;
        line-height: 36px;
        padding: 0 5px;
        border-bottom: 1px solid #ddd;
    }

    li label {
        float: left;
        cursor: pointer;
    }

    li label li input {
        vertical-align: middle;
        margin-right: 6px;
        position: relative;
        top: -1px;
    }

    li button {
        float: right;
        display: none;
        margin-top: 3px;
    }

    li:before {
        content: initial;
    }

    li:last-child {
        border-bottom: none;
    }

    li:hover{
        background-color: yellowgreen;
    }

    li:hover button{
        display: block;
    }



    /* .todo-enter-active{
        animation: xiaolin 1s;
    }
    .todo-leave-active{
        animation: xiaolin 1s reverse;
    }

    @keyframes xiaolin {
        from{
            transform: translateX(+100%);
        }
        to{
            transform: translateX(0px);
        }
    } */
</style>

41、Vue脚手架配置代理服务器

方法一

在vue.config.js中添加如下配置:

devServer:{
  proxy:"http://localhost:5000"
}

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)

方法二

编写vue.config.js配置具体代理规则:

module.exports = {
    devServer: {
      proxy: {
      '/api1': {// 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api1': ''}
      },
      '/api2': {// 匹配所有以 '/api2'开头的请求路径
        target: 'http://localhost:5001',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api2': ''}
      }
    }
  }
}
/*
   changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
   changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
   changeOrigin默认值为true
*/

说明:

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。

跨域请求:协议、域名、端口号

解决跨域:1、cors 2、jsonp 3、代理服务器 4、Nginx反向代理

服务器之间不使用ajax请求,没有跨域问题,不受同源策略影响

源码

App.vue

<template>
    <div id="root">
        <button @click="getStudnets">获取学生信息</button>
        <button @click="getCars">获取汽车信息</button>
    </div>
</template>

<script>
    import axios from 'axios'
    export default {
        name:'App',
        methods: {
            getStudnets(){
                axios.get('http://localhost:8080/xiaolin/students').then(
                    response=>{
                        console.log('请求成功了',response.data);
                    },
                    error=>{
                        console.log('请求失败了',error.message);
                    }
                )
            },
            getCars(){
                axios.get('http://localhost:8080/lxg/cars').then(
                    response=>{
                        console.log('请求成功了',response.data);
                    },
                    error=>{
                        console.log('请求失败了',error.message);
                    }
                )
            }
        },
    }
</script>


main.js

// 引入Vue
import Vue from "vue";
// 引入App
import App from './App.vue';


// 关闭生产提示
Vue.config.productionTip=false;



// 创建vm
new Vue({ 
    el:'#app',
    render:h=>h(App),
    beforeCreate(){
        Vue.prototype.$bus = this; // 安装全局事件总线
    }
});


vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  //开启代理服务器(方式一)
 /*  devServer:{
    proxy: 'http://localhost:5000'
  } */
  //开启代理服务器(方式二)
  devServer:{
    proxy:{
        '/xiaolin':{
            target: 'http://localhost:5000',
            // 匹配所有/xiaolin开头的替换成空字符串
            pathRewrite:{'^/xiaolin':''},
            // ws:true, //用于支持websocket,默认true
            // changeOrigin: true //用于控制请求头中的host值,默认是true
        },
        '/lxg':{
            target: 'http://localhost:5001',
            // 匹配所有/xiaolin开头的替换成空字符串
            pathRewrite:{'^/lxg':''},
            // ws:true, //用于支持websocket,默认true
            // changeOrigin: true //用于控制请求头中的host值,默认是true
        },
    }
  }
})

42、GitHub用户搜索案例

接口地址:api.github.com/search/user…

image-20221109165706782

image-20221109165753117

image-20221109165808778

image-20221109165948770

1441607086860827

源码

MyList.vue

<template>
    <div class="row">
        <!-- 展示用户列表 -->
        <div v-show="info.users.length" class="card" v-for="user in info.users" :key="user.id" >
            <a :href="user.html_url" target="_blank">
            <img :src="user.avatar_url" style='width:100px'/>
            </a>
            <p class="card-text">{{user.login}}</p>
        </div>
        <!-- 展示欢迎词 -->
        <h1 v-show="info.isFirst">欢迎使用Github用户查询中心!</h1>
        <!-- 展示加载中 -->
        <div v-show="info.isLoading">
            <img src="../assets/img/loading.gif" alt="">
            <span class="loading">正在努力加载中......请您耐心等待!</span>
        </div>
        <!-- 展示错误信息 -->
        <h1 v-show="info.errMsg">您的请求出错啦!{{info.errMsg}}</h1>
    </div>
</template>

<script>
    export default {
        name:'MyList',
        data(){
            return {
                info:{
                    isFirst:true,
                    isLoading:false,
                    errMsg:'',
                    users:[]
                }
            }
        },
        mounted(){
            // this.$bus.$on('updateListData',(isFirst,isLoading,errMsg,users)=>{
            this.$bus.$on('updateListData',(dataObj)=>{
                // console.log("我是List组件,我收到了数据:",users);
                this.info= {...this.info,...dataObj};
                /* this.users=users;
                this.isFirst=isFirst;
                this.isLoading=isLoading;
                this.errMsg=errMsg; */
            });
        }
    }
</script>

<style scoped>

    .album {
        min-height: 50rem; /* Can be removed; just added for demo purposes */
        padding-top: 3rem;
        padding-bottom: 3rem;
        background-color: #f7f7f7;
    }

    .card {
        float: left;
        width: 33.333%;
        padding: .75rem;
        margin-bottom: 2rem;
        border: 1px solid #efefef;
        text-align: center;
    }

    .card > img {
        margin-bottom: .75rem;
        border-radius: 100px;
    }

    .card-text {
        font-size: 85%;
    }

    .loading{
        font-size: 40px;
    }
</style>

Search.vue

<template>
    <section class="jumbotron">
        <h3 class="jumbotron-heading">Search Github Users</h3>
        <div>
            <input v-model="keyWord" type="text" placeholder="enter the name you search"/>&nbsp;
            <button @click="searchUsers">Search</button>
        </div>
    </section>
</template>

<script>
    import axios from 'axios';
    export default {
        name:'SearchS',
        data(){
            return{
                keyWord:'',
            }
        },
        methods: {
            searchUsers(){
                // 请求更新List的数据
                // this.$bus.$emit('updateListData',false,true,'',[]);
                this.$bus.$emit('updateListData',{isFirst:false,isLoading:true,errMsg:'',users:[]});
                //https://api.github.com/search/users?q=${this.keyWord}
                axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                    response => {
                        console.log('请求成功了',response.data.items);
                        // this.$bus.$emit('getUsers',response.data.items);
                        // this.$bus.$emit('updateListData',false,false,'',response.data.items)
                        // 请求成功后
                        this.$bus.$emit('updateListData',{isLoading:false,errMsg:'',users:response.data.items});

                    },
                    error =>{
                        console.log('请求失败了',error.message);
                        // 请求失败后
                        this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]});
                    }
                );
            }
        },
    }
</script>

App.vue

<template>
    <div class="container">
        <Search/>
        <MyList/>
    </div>
</template>

<script>
    // import './assets/css/bootstrap.css'
    import Search from './components/Search'
    import MyList from './components/MyList'
	export default {
		name:'App',
        components:{
            Search,
            MyList
        }
    }
</script>


main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	beforeCreate() {
		Vue.prototype.$bus = this;
	},
})

bootstrap.css上官网下载

43、github搜索案例----vue-resource

现已不维护,不推荐使用,但需要了解一下

1、安装插件库:npm i vue-resource

2、引入插件库:import vueResource from 'vue-resource'

3、使用插件库:Vue.use(vueResource)

4、在Search.vue中:只需要将axios更改为this.$http即可,功能一模一样

44、slot插槽

1、效果一(不使用插槽)

image-20221109174904107

2、效果二(默认插槽)

c0e207ce23c880b0c5bc49b685720b8

image-20221109175051775

Category.vue

<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <!-- <ul>
            <li v-for="(item,index) in listData" :key="index">{{item}}</li>
        </ul> -->
        <!-- <img v-show="title=='美食'" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg"> -->
        <!-- 定义一个插槽(占个位,等着组件的使用者进行填充) -->
        <slot>默认值,若使用者没有传具体结构,我会出现</slot>
    </div>
</template>

App.vue

<template>
    <div class="container">
        <Category title="美食" :listData="foods">
            <img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg">
        </Category>
        <Category title="游戏" :listData="games">
            <ul>
                <li v-for="(game,index) in games" :key="index">{{game}}</li>
            </ul>
        </Category>
        <Category title="电影" :listData="films">
            <video controls  src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
        </Category>
    </div>
</template>

image-20221109192406865

3、具名插槽

Category.vue

<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <!-- <ul>
            <li v-for="(item,index) in listData" :key="index">{{item}}</li>
        </ul> -->
        <!-- <img v-show="title=='美食'" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg"> -->
        <!-- 定义一个插槽(占个位,等着组件的使用者进行填充) -->
        <slot name="center">默认值,若使用者没有传具体结构,我会出现</slot>
        <slot name="footer">默认值,若使用者没有传具体结构,我会出现</slot>
    </div>
</template>

App.vue

<template>
    <div class="container">
        <Category title="美食" :listData="foods">
            <img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg">
            <a slot="footer" href="https://www.bilibili.com">更多美食</a>
        </Category>
        <Category title="游戏" :listData="games">
            <ul slot="center">
                <li v-for="(game,index) in games" :key="index">{{game}}</li>
            </ul>
            <div slot="footer" class="foot">
                <a  href="https://www.bilibili.com">单击游戏</a>
                <a  href="https://www.bilibili.com">网络游戏</a>
            </div>
        </Category>
        <Category title="电影" :listData="films">
            <video slot="center" controls  src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
            <template  v-slot:footer>
                <div class="foot">
                    <a  href="https://www.bilibili.com">经典</a>
                    <a  href="https://www.bilibili.com">热门</a>
                    <a  href="https://www.bilibili.com">推荐</a>
                </div>
                <h4>欢迎前来观影</h4>
            </template>
        </Category>
    </div>
</template>

4、作用域插槽

App.vue

<template>
    <div class="container">
       
        <Category title="游戏">
            <template scope="xiaolin">
                <ul>
                    <li v-for="(game,index) in xiaolin.games" :key="index">{{game}}</li>
                </ul>
            </template>
        </Category>
        <Category title="游戏" >
            <template scope='{games}'>
                <ol>
                    <li v-for="(game,index) in games" :key="index">{{game}}</li>
                </ol>
            </template>
            
        </Category>
        <Category title="游戏">
            <template slot-scope="{games}">
                <h4 v-for="(game,index) in games" :key="index">{{game}}</h4>
            </template>
        </Category>
    </div>
</template>

Category.vue

<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <slot :games="games" msg="哈哈哈">默认值,若使用者没有传具体结构,我会出现</slot>
    </div>
</template>

5、总结

  1. 作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件

  2. 分类:默认插槽、具名插槽、作用域插槽

  3. 使用方式:

    1. 默认插槽:

      父组件中:
              <Category>
                 <div>html结构1</div>
              </Category>
      子组件中:
              <template>
                  <div>
                     <!-- 定义插槽 -->
                     <slot>插槽默认内容...</slot>
                  </div>
              </template>
      
    2. 具名插槽:

      父组件中:
              <Category>
                  <template slot="center">
                    <div>html结构1</div>
                  </template>
      
                  <template v-slot:footer>
                     <div>html结构2</div>
                  </template>
              </Category>
      子组件中:
              <template>
                  <div>
                     <!-- 定义插槽 -->
                     <slot name="center">插槽默认内容...</slot>
                     <slot name="footer">插槽默认内容...</slot>
                  </div>
              </template>
      
    3. 作用域插槽:

      1. 理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

      2. 具体编码:

        父组件中:
               <Category>
                   <template scope="scopeData">
                       <!-- 生成的是ul列表 -->
                       <ul>
                           <li v-for="g in scopeData.games" :key="g">{{g}}</li>
                       </ul>
                   </template>
               </Category>
        
               <Category>
                   <template slot-scope="scopeData">
                       <!-- 生成的是h4标题 -->
                       <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
                   </template>
               </Category>
        子组件中:
                <template>
                    <div>
                        <slot :games="games"></slot>
                    </div>
                </template>
               
                <script>
                    export default {
                        name:'Category',
                        props:['title'],
                        //数据在子组件自身
                        data() {
                            return {
                                games:['红色警戒','穿越火线','劲舞团','超级玛丽']
                            }
                        },
                    }
                </script>
        

45、vuex

1、理解vuex

1、vuex是什么?

1、概念:专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对Vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于组件间通信。
2、GitHub地址:https://github.com/vuejs/vuex

2、什么时候使用vuex

  1. 多个组件依赖同一状态
  2. 来自不同组件的行为需要变更同一状态

image-20221109211649101

image-20221109233034400

2、案例-vue版本

Count.vue

<template>
    <div>
        <h1>当前求和为:{{sum}}</h1>
        <select v-model.number="n">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <!-- <option :value="1">1</option>
            <option :value="2">2</option>
            <option :value="3">3</option> -->
        </select>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
        <button @click="incrementOdd">当前求和为奇数再加</button>
        <button @click="incrementWait">等一等再加</button>

    </div>
</template>
<script>

    export default {
        name:'CountS',
        data(){
            return{
                sum:0,//当前的和
                n:1,//用户选中的数字
            }
        },
        methods:{
            increment(){
                this.sum+=this.n;
            },
            decrement(){
                this.sum-=this.n;
            },
            incrementOdd(){
                if(this.sum%2){
                    this.sum+=this.n;
                }
            },
            incrementWait(){
                setTimeout(()=>{
                    this.sum+=this.n;
                },300);
            },
        }
    }
</script>

<style scoped>
    button{
        margin-right: 10px;
    }
</style>

App.vue

<template>
    <div>
        <Count></Count>
    </div>
</template>

<script>
    import Count from './components/Count'
	export default {
		name:'App',
        components:{
            Count
        },
        
    }
</script>



main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'
//关闭Vue的生产提示
Vue.config.productionTip = false
// 使用插件
Vue.use(vueResource)
//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	beforeCreate() {
		Vue.prototype.$bus = this;
	},
})

3、Vuex工作原理图

vuex

Mutate:包含多个直接更新state的方法,值为对象,不能写异步代码

State:vuex管理的状态对象------保存数据,唯一的

Actions:包含多个响应用户动作的回调函数,值为对象;通过commit()触发mutation函数调用,间接更新state;使用dispatch触发actions中的回调;可以包含异步代码

getters:包含多个用于返回数据的函数,值为对象

modules:包含多个module,一个module就是一个store的配置对象,与一个组件(包含有共享数据)对应

4、搭建vuex环境

1、npm i vuex

2、Vue.use(Vuex)

3、store

4、vc=>store

vue2中用vuex的3版本:npm i vuex@3

vue3中用vuex的4版本

1、在src下新建文件夹store,在文件夹中新建文件index.js
2、在main.js中引入store
3、在new Vue中添加store配置项

index.js

// 该文件用于创建Vuex中最为核心的store

import Vue from 'vue'
// 引入Vuex
import Vuex from 'vuex'
Vue.use(Vuex)
// 准备actions---用于响应组件中的动作
const actions = {}
// 准备mutations---用于操作数据(state)
const mutations = {}
// 准备state---用于存储数据
const state = {}


// 创建store 暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
})


5、vuex实现案例

Count.vue

<template>
    <div>
        <h1>当前求和为:{{$store.state.sum}}</h1>
        <select v-model.number="n">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <!-- <option :value="1">1</option>
            <option :value="2">2</option>
            <option :value="3">3</option> -->
        </select>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
        <button @click="incrementOdd">当前求和为奇数再加</button>
        <button @click="incrementWait">等一等再加</button>

    </div>
</template>
<script>

    export default {
        name:'CountS',
        data(){
            return{
                n:1,//用户选中的数字
            }
        },
        methods:{
            increment(){
                // this.$store.dispatch('add',this.n);
                this.$store.commit('ADD',this.n);
            },
            decrement(){
                // this.$store.dispatch('decrement',this.n);
                this.$store.commit('DECREMENT',this.n);
            },
            incrementOdd(){
                /* if(this.$store.state.sum % 2){
                    this.$store.dispatch('add',this.n);
                } */
                this.$store.dispatch('addOdd',this.n);
            },
            incrementWait(){
                /* setTimeout(()=>{
                    this.$store.dispatch('add',this.n);
                },500); */
                this.$store.dispatch('addWait',this.n);
            },
        },

    }
</script>

<style scoped>
    button{
        margin-right: 10px;
    }
</style>

index.js

// 该文件用于创建Vuex中最为核心的store

import Vue from 'vue'
// 引入Vuex
import Vuex from 'vuex'
Vue.use(Vuex)
// 准备actions---用于响应组件中的动作
const actions = {
    /* add(context,value){
        // console.log('actions中的add被调用了',context,value);
        context.commit('ADD',value);
    },
    decrement(context,value){
        context.commit('DECREMENT',value);
    }, */

    addOdd(context,value){
        // console.log('actions中的add被调用了',context,value);
        if(context.state.sum % 2){
            context.commit('ADD',value);
        }
    },

    addWait(context,value){
        // console.log('actions中的add被调用了',context,value);
        setTimeout(()=>{
            context.commit('ADD',value);
        },500)
    },
    
}
// 准备mutations---用于操作数据(state)
const mutations = {
    ADD(state,value){
        // console.log('mutations中的ADD被调用了',state,value);
        state.sum+=value;
    },
    DECREMENT(state,value){
        state.sum-=value;
    }
}
// 准备state---用于存储数据
const state = {
    sum:0,//当前的和
}


// 创建store 暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
})


App.vue

<template>
    <div>
        <Count></Count>
    </div>
</template>

<script>
    import Count from './components/Count'
	export default {
		name:'App',
        components:{
            Count
        },
        mounted() {
            console.log('App',this);

        },
    }
</script>



main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'

// 引入store
import store from './store'


//关闭Vue的生产提示
Vue.config.productionTip = false
// 使用插件
Vue.use(vueResource)
// Vue.use(Vuex)
//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	beforeCreate() {
		Vue.prototype.$bus = this;
	},
    // store:'hello',
    store,
    data:{
        msg:'test'
    }
})

6、总结

  1. 初始化数据、配置actions、配置mutations,操作文件store.js

    //引入Vue核心库
    import Vue from 'vue'
    //引入Vuex
    import Vuex from 'vuex'
    //引用Vuex
    Vue.use(Vuex)
    
    const actions = {
        //响应组件中加的动作
     jia(context,value){
         // console.log('actions中的jia被调用了',miniStore,value)
         context.commit('JIA',value)
     },
    }
    
    const mutations = {
        //执行加
     JIA(state,value){
         // console.log('mutations中的JIA被调用了',state,value)
         state.sum += value
     }
    }
    
    //初始化数据
    const state = {
       sum:0
    }
    
    //创建并暴露store
    export default new Vuex.Store({
     actions,
     mutations,
     state,
    })
    
  2. 组件中读取vuex中的数据:$store.state.sum

  3. 组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)$store.commit('mutations中的方法名',数据)

    备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit

7、getters的使用

  1. 概念:当state中的数据需要经过加工后再使用时,可以使用getters加工。

  2. store.js中追加getters配置

    ......
    
    const getters = {
     bigSum(state){
         return state.sum * 10
     }
    }
    
    //创建并暴露store
    export default new Vuex.Store({
     ......
     getters
    })
    
  3. 组件中读取数据:$store.getters.bigSum

1、修改index.js

// 准备getters----用于量state中的数据进行加工
const getters = {
    bigSum(state){
        return state.sum*10
    }
}

// 创建store 暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})

2、 修该Count.vue

  <h3>当前求和的10倍是:{{$store.getters.bigSum}}</h3>

8、mapState与mapGetters

修改Count.vue

	    <h1>当前求和为:{{sum}}</h1>
        <h3>当前求和的10倍是:{{bigSum}}</h3>
        <h3>我在{{school}},学习{{subject}}</h3>


computed:{
            // 靠程序员自己去写计算属性
            /* he(){
                return this.$store.state.sum
            },
            xuexiao(){
                return this.$store.state.school
            },
            subject(){
                return this.$store.state.subject
            }, */
            
            sum(){
                return this.$store.state.sum
            },
            school(){
                return this.$store.state.school
            },
            subject(){
                return this.$store.state.subject
            },
            
            // 借助mapState生成计算属性,从state读取数据(对象写法)
            // ...mapState({he:'sum',xuexiao:'school',subject:'subject'}),

            // 借助mapState生成计算属性,从state读取数据(数组写法)
            ...mapState(['sum','school','subject']),

            /* ******************************* */
            /* bigSum(){
                return this.$store.getters.bigSum
            }, */

            // 借助mapGetters生成计算属性,从state读取数据(对象写法)
            // ...mapGetters({bigSum:'bigSum'})
            // 借助mapGetters生成计算属性,从state读取数据(数组写法)
            ...mapGetters(['bigSum'])
        },

9、mapMutation和mapActions

修改Count.vue

	    <button @click="increment(n)">+</button>
        <button @click="decrement(n)">-</button>
        <button @click="incrementOdd(n)">当前求和为奇数再加</button>
        <button @click="incrementWait(n)">等一等再加</button>



methods:{
            // 自己写
            /* increment(){
                this.$store.commit('ADD',this.n);
            },
            decrement(){
                this.$store.commit('DECREMENT',this.n);
            }, */

            // 借助mapMutations生成对应的方法,方法中会调用commit去联系mutation(对象写法)
            ...mapMutations({increment:'ADD',decrement:'DECREMENT'}),
            // 借助mapMutations生成对应的方法,方法中会调用commit去联系mutation(数组写法)
            // ...mapMutations(['ADD','DECREMENT']),
            /* ************************************* */

            /* incrementOdd(){
                this.$store.dispatch('addOdd',this.n);
            },
            incrementWait(){
                this.$store.dispatch('addWait',this.n);
            }, */

            ...mapActions({incrementOdd:'addOdd',incrementWait:'addWait'}),
            // ...mapActions(['addOdd','addWait']),

            
        },

10、四个map方法总结

  1. mapState方法:用于帮助我们映射state中的数据为计算属性

    computed: {
        //借助mapState生成计算属性:sum、school、subject(对象写法)
         ...mapState({sum:'sum',school:'school',subject:'subject'}),
             
        //借助mapState生成计算属性:sum、school、subject(数组写法)
        ...mapState(['sum','school','subject']),
    },
    
  2. mapGetters方法:用于帮助我们映射getters中的数据为计算属性

    computed: {
        //借助mapGetters生成计算属性:bigSum(对象写法)
        ...mapGetters({bigSum:'bigSum'}),
    
        //借助mapGetters生成计算属性:bigSum(数组写法)
        ...mapGetters(['bigSum'])
    },
    
  3. mapActions方法:用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数

    methods:{
        //靠mapActions生成:incrementOdd、incrementWait(对象形式)
        ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
        //靠mapActions生成:incrementOdd、incrementWait(数组形式)
        ...mapActions(['jiaOdd','jiaWait'])
    }
    
  4. mapMutations方法:用于帮助我们生成与mutations对话的方法,即:包含$store.commit(xxx)的函数

    methods:{
        //靠mapActions生成:increment、decrement(对象形式)
        ...mapMutations({increment:'JIA',decrement:'JIAN'}),
        
        //靠mapMutations生成:JIA、JIAN(对象形式)
        ...mapMutations(['JIA','JIAN']),
    }
    

备注:mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

11、多组件共享数据

新建Person.vue

<template>
    <div>
        <h1>人员列表</h1>
        <h3 style="color:red">Count组件的求和为:{{sum}}</h3>
        <input type="text" placeholder="请输入姓名" v-model="name">
        <button @click="add">添加</button>
        <ul>
            <li v-for="p in personList" :key="p.id">{{p.name}}</li>        </ul>
    </div>
</template>

<script>
import {nanoid} from 'nanoid'
// import { mapState } from 'vuex'
    export default {
        name:"PersonS",
        data(){
            return{
                name:''
            }
        },
        computed:{
            personList(){
                return this.$store.state.personList;
            },
            sum(){
                return this.$store.state.sum;
            }

            // ...mapState(['personList']),
        },
        methods:{
            add(){
                const personObj = {id:nanoid(),name:this.name}
                // console.log(person);
                this.$store.commit('ADD_PERSON',personObj)
                this.name = ''
            }
        }
    }
</script>

<style>

</style>

修改index.js

// 准备mutations---用于操作数据(state)
const mutations = {
    ADD(state,value){
        console.log('mutations中的ADD被调用了',state,value);
        state.sum+=value;
    },
    DECREMENT(state,value){
        state.sum-=value;
    },
    ADD_PERSON(state,value){
        console.log('mutations中的ADD_PERSON被调用了',state,value);
        state.personList.unshift(value)
    }
}
// 准备state---用于存储数据
const state = {
    sum:0,//当前的和
    school:'尚硅谷',
    subject:'前端',
    personList:[
        {id:'001',name:'张三'}
    ]
}

在Count组件中使用personList数据

<h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
 ...mapState(['sum','school','subject','personList']),

12、模块化和命名空间

  1. 目的:让代码更好维护,让多种数据分类更加明确。

  2. 修改store.js

    const countAbout = {
      namespaced:true,//开启命名空间
      state:{x:1},
      mutations: { ... },
      actions: { ... },
      getters: {
        bigSum(state){
           return state.sum * 10
        }
      }
    }
    
    const personAbout = {
      namespaced:true,//开启命名空间
      state:{ ... },
      mutations: { ... },
      actions: { ... }
    }
    
    const store = new Vuex.Store({
      modules: {
        countAbout,
        personAbout
      }
    })
    
  3. 开启命名空间后,组件中读取state数据:

    //方式一:自己直接读取
    this.$store.state.personAbout.list
    //方式二:借助mapState读取:
    ...mapState('countAbout',['sum','school','subject']),
    
  4. 开启命名空间后,组件中读取getters数据:

    //方式一:自己直接读取
    this.$store.getters['personAbout/firstPersonName']
    //方式二:借助mapGetters读取:
    ...mapGetters('countAbout',['bigSum'])
    
  5. 开启命名空间后,组件中调用dispatch

    //方式一:自己直接dispatch
    this.$store.dispatch('personAbout/addPersonWang',person)
    //方式二:借助mapActions:
    ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
  6. 开启命名空间后,组件中调用commit

    //方式一:自己直接commit
    this.$store.commit('personAbout/ADD_PERSON',person)
    //方式二:借助mapMutations:
    ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
    

源码

Count.vue
<template>
    <div>
        <h1>当前求和为:{{sum}}</h1>
        <h3>当前求和的10倍是:{{bigSum}}</h3>
        <h3>我在{{school}},学习{{subject}}</h3>
        <h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
        <select v-model.number="n">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
        <button @click="increment(n)">+</button>
        <button @click="decrement(n)">-</button>
        <button @click="incrementOdd(n)">当前求和为奇数再加</button>
        <button @click="incrementWait(n)">等一等再加</button>

    </div>
</template>
<script>
    import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
    export default {
        name:'CountS',
        data(){
            return{
                n:1,//用户选中的数字
            }
        },
        computed:{

            // 借助mapState生成计算属性,从state读取数据(数组写法)
            // ...mapState(['countAbout','personAbout']),
            ...mapState('countAbout',['sum','school','subject']),
            ...mapState('personAbout',['personList']),
            // 借助mapGetters生成计算属性,从state读取数据(数组写法)
            ...mapGetters('countAbout',['bigSum'])
        },
        methods:{
           
            // 借助mapMutations生成对应的方法,方法中会调用commit去联系mutation(对象写法)
            ...mapMutations('countAbout',{increment:'ADD',decrement:'DECREMENT'}),

            ...mapActions('countAbout',{incrementOdd:'addOdd',incrementWait:'addWait'}),

            
        },
        mounted(){
            // const x = mapState({he:'sum',xuexiao:'school',subject:'subject'})
            // console.log(x);
        }
    }
</script>

<style scoped>
    button{
        margin-right: 10px;
    }
</style>
Person.vue
<template>
    <div>
        <h1>人员列表</h1>
        <h3 style="color:red">Count组件的求和为:{{sum}}</h3>
        <h3>列表中第一个人的名字是:{{firstPersonName}}</h3>
        <input type="text" placeholder="请输入姓名" v-model="name">
        <button @click="add">添加</button>
        <button @click="addWang">添加一个姓王的人</button>
        <button @click="addText">添加一句话</button>
        <ul>
            <li v-for="p in personList" :key="p.id">{{p.name}}</li>        </ul>
    </div>
</template>

<script>
import {nanoid} from 'nanoid'
// import { mapState } from 'vuex'
    export default {
        name:"PersonS",
        data(){
            return{
                name:''
            }
        },
        computed:{
            personList(){
                return this.$store.state.personAbout.personList;
            },
            sum(){
                return this.$store.state.countAbout.sum;
            },
            firstPersonName(){
                return this.$store.getters['personAbout/firstPersonName']
            }

            // ...mapState(['personList']),
        },
        methods:{
            add(){
                const personObj = {id:nanoid(),name:this.name}
                // console.log(person);
                this.$store.commit('personAbout/ADD_PERSON',personObj)
                this.name = ''
            },
            addWang(){
                const personObj = {id:nanoid(),name:this.name}
                this.$store.dispatch('personAbout/addPersonWang',personObj)
                this.name = ''
            },
            addText(){
                this.$store.dispatch('personAbout/addPersonServer')
            }
            
        }
    }
</script>

<style>

</style>
App.vue
<template>
    <div>
        <Count></Count>
        <hr>
        <Person></Person>
    </div>
</template>

<script>
    import Count from './components/Count'
    import Person from './components/Person'
	export default {
		name:'App',
        components:{
            Count,
            Person
        },
        mounted() {
            // console.log('App',this);

        },
    }
</script>



main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import vueResource from 'vue-resource'

// 引入store
import store from './store'


//关闭Vue的生产提示
Vue.config.productionTip = false
// 使用插件
Vue.use(vueResource)
// Vue.use(Vuex)
//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	beforeCreate() {
		Vue.prototype.$bus = this;
	},
    // store:'hello',
    store,
    data:{
        msg:'test'
    }
})
count.js
// 求和组件相关的配置
const countOptions = {
    namespaced:true,
    actions:{
        addOdd(context,value){
            console.log('actions中的add被调用了',context,value);
            if(context.state.sum % 2){
                context.commit('ADD',value);
            }
        },
        addWait(context,value){
            // console.log('actions中的add被调用了',context,value);
            setTimeout(()=>{
                context.commit('ADD',value);
            },500)
        },
    },
    mutations:{
        ADD(state,value){
            console.log('mutations中的ADD被调用了',state,value);
            state.sum+=value;
        },
        DECREMENT(state,value){
            state.sum-=value;
        },
    },
    state:{
        sum:0,//当前的和
        school:'尚硅谷',
        subject:'前端',
    },
    getters:{
        bigSum(state){
            return state.sum*10
        }
    }
}

export default countOptions
person.js
// 人员管理组件相关的配置

import axios from "axios";
import { nanoid } from "nanoid";
const personOptions = {
    namespaced:true,
    actions:{
        addPersonWang(context,value){
            // console.log(context,value)
            if(value.name.indexOf('王')===0){
                context.commit('ADD_PERSON',value)
            }else{
                alert('只能添加姓王的人哦')
            }
        },
        addPersonServer(context){
            axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
                response=>{
                    context.commit('ADD_PERSON',{id:nanoid(),name:response.data})
                },
                error=>{
                    alert(error.message)
                }
            )
        }
    },
    mutations:{
        ADD_PERSON(state,value){
            console.log('mutations中的ADD_PERSON被调用了',state,value);
            state.personList.unshift(value)
        }
    },
    state:{
        personList:[
            {id:'001',name:'张三'}
        ]
    },
    getters:{
        firstPersonName(state){
            return state.personList[0].name
        }
    }
}

export default personOptions
index.js
// 该文件用于创建Vuex中最为核心的store

import Vue from 'vue'
// 引入Vuex
import Vuex from 'vuex'

import countOptions from './count'
import personOptions from './person'

Vue.use(Vuex)





// 创建store 暴露store
export default new Vuex.Store({
    modules:{
        countAbout:countOptions,
        personAbout:personOptions
    }
})


46、vue-router

1、基本介绍

image-20221110195136616

image-20221110195047426

1、理解:vue的一个插件库,专门用来实现SPA应用

2、SPA的理解

1、单页Web应用(single page web application,SPA)
2、整个应用只有一个完整的页面
3、点击页面中的导航链接不会刷新页面,只会做页面的局部更新
4、数据需要通过ajax请求获取

3、路由的理解

1、什么是路由
	1.一个路由就是一组映射关系(key - value) 
	2. key 为路径, value 可能是 function 或 component 
2、路由分类
	1. 后端路由: 
		1) 理解:value 是 function, 用于处理客户端提交的请求。 
		2) 工作过程:服务器接收到一个请求时, 根据请求路径找到匹配的函数 来处理请求, 返回响应数据。 
	2. 前端路由: 
		1) 理解:value 是 component,用于展示页面内容。 
		2) 工作过程:当浏览器的路径改变时, 对应的组件就会显示

2、基本路由

  1. 安装vue-router,命令:npm i vue-router@3

  2. 应用插件:Vue.use(VueRouter)

  3. 编写router配置项:

    //引入VueRouter
    import VueRouter from 'vue-router'
    //引入Luyou 组件
    import About from '../components/About'
    import Home from '../components/Home'
    
    //创建router实例对象,去管理一组一组的路由规则
    const router = new VueRouter({
     routes:[
         {
             path:'/about',
             component:About
         },
         {
             path:'/home',
             component:Home
         }
     ]
    })
    
    //暴露router
    export default router
    
  4. 实现切换(active-class可配置高亮样式)

    <router-link active-class="active" to="/about">About</router-link>
    
  5. 指定展示位置

    <router-view></router-view>
    

源码

About.vue
<template>
<h2>我是About的内容</h2>
</template>

<script>
export default {
name:"AboutMe"
}
</script>


Home.vue
<template>
<h2>我是Home的内容</h2>
</template>

<script>
export default {
name:"TheHome"
}
</script>

router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../components/About'
import Home from '../components/Home'
// 创建一个路由器
const router = new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home
},
]
})


export default router
App.vue
<template>
<div>
<div class="row">
<div class="col-xs-offset-2 col-xs-8">
<div class="page-header">
<h2>Vue Router Demo</h2>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<div class="list-group">
<!-- 原始html我们使用a标签实现页面的跳转  -->
<!-- <a class="list-group-item active" href="./about.html">About</a> -->
<!-- <a class="list-group-item" href="./home.html">Home</a> -->

<!-- Vue中接祖router-link实现路径切换 -->
<router-link class="list-group-item" active-class="active" to="/about">About</router-link>
<router-link class="list-group-item" active-class="active" to="/home">Home</router-link>

</div>
</div>
<div class="col-xs-6">
<div class="panel">
<div class="panel-body">
<!-- 此处看用户点击什么,再展示什么 -->
<!-- 指定组件的呈现位置 -->
<router-view></router-view>
</div>
</div>
</div>
</div>
</div>
</template>

<script>
export default {
name:'App',
}
</script>



main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
// 引入VueRouter
import VueRouter from 'vue-router'
// 引入路由器
import router from './router'
//关闭Vue的生产提示
Vue.config.productionTip = false
// 应用插件
Vue.use(VueRouter)
//创建vm
new Vue({
el:'#app',
render: h => h(App),
router:router
})

3、几个注意点

  1. 路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹。

  2. 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。

  3. 每个组件都有自己的$route属性,里面存储着自己的路由信息。

  4. 整个应用只有一个router,可以通过组件的$router属性获取到。

4、嵌套(多级)路由

  1. 配置路由规则,使用children配置项:

    routes:[
     {
         path:'/about',
         component:About,
     },
     {
         path:'/home',
         component:Home,
         children:[ //通过children配置子级路由
             {
                 path:'news', //此处一定不要写:/news
                 component:News
             },
             {
                 path:'message',//此处一定不要写:/message
                 component:Message
             }
         ]
     }
    ]
    
  2. 跳转(要写完整路径):

    <router-link to="/home/news">News</router-link>
    

源码

Banner.vue
<template>
<div class="col-xs-offset-2 col-xs-8">
<div class="page-header">
<h2>Vue Router Demo</h2>
</div>
</div>
</template>

<script>
export default {
name:"BannerS"
}
</script>

Home.vue
<template>
<div>
<h2>Home组件内容</h2>
<div>
<ul class="nav nav-tabs">
<li>
<router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>
</li>
<li>
<router-link class="list-group-item" active-class="active" to="/home/message">Message</router-link>
</li>
</ul>
<router-view></router-view>
</div>
</div>
</template>

<script>
export default {
name:"TheHome",
/* beforeDestroy() {
console.log("home即将销毁了")
}, */
/* mounted(){
console.log("home挂载好了",this);
window.hoemRoute = this.$route
window.homeRouter = this.$router
} */
}
</script>

Message.vue
<template>
<div>
<ul>
<li>
<a href="/message1">message001</a>&nbsp;&nbsp;
</li>
<li>
<a href="/message2">message002</a>&nbsp;&nbsp;
</li>
<li>
<a href="/message/3">message003</a>&nbsp;&nbsp;
</li>
</ul>
</div>
</template>

<script>
export default {
name:"MessageS"
}
</script>


News.vue
<template>
<ul>
<li>news001</li>
<li>news002</li>
<li>news003</li>
</ul>
</template>

<script>
export default {
name:"NewS"
}
</script>


router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
// 创建一个路由器
const router = new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home,
children:[
{
path:"message",
component:Message,
},
{
path:"news",
component:News,
}
]
},
]
})


export default router
App.vue
<template>
<div>
<div class="row">
<Banner></Banner>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<div class="list-group">
<!-- 原始html我们使用a标签实现页面的跳转  -->
<!-- <a class="list-group-item active" href="./about.html">About</a> -->
<!-- <a class="list-group-item" href="./home.html">Home</a> -->

<!-- Vue中接祖router-link实现路径切换 -->
<router-link class="list-group-item" active-class="active" to="/about">About</router-link>
<router-link class="list-group-item" active-class="active" to="/home">Home</router-link>

</div>
</div>
<div class="col-xs-6">
<div class="panel">
<div class="panel-body">
<!-- 此处看用户点击什么,再展示什么 -->
<!-- 指定组件的呈现位置 -->
<router-view></router-view>
</div>
</div>
</div>
</div>
</div>
</template>

<script>
import Banner from './components/Banner'
export default {
name:'App',
components:{
Banner
}
}
</script>



main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
// 引入VueRouter
import VueRouter from 'vue-router'
// 引入路由器
import router from './router'
//关闭Vue的生产提示
Vue.config.productionTip = false
// 应用插件
Vue.use(VueRouter)
//创建vm
new Vue({
el:'#app',
render: h => h(App),
router:router
})
About.vue
<template>
<h2>我是About的内容</h2>
</template>

<script>
export default {
name:"AboutMe",
/* beforeDestroy() {
console.log("about即将销毁了")
}, */
mounted(){
console.log("about挂载好了",this);
window.aboutRoute = this.$route
window.aboutRouter = this.$router
}
}
</script>


5、路由传参

  1. 传递参数

    <!-- 跳转并携带query参数,to的字符串写法 -->
    <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link>
                 
    <!-- 跳转并携带query参数,to的对象写法 -->
    <router-link 
     :to="{
         path:'/home/message/detail',
         query:{
            id:666,
                title:'你好'
         }
     }"
    >跳转</router-link>
    
  2. 接收参数:

    $route.query.id
    $route.query.title
    

源码

Detail.vue
<template>
    <ul>
        <li>消息编号:{{$route.query.id}}</li>
        <li>消息标题:{{$route.query.title}}</li>
    </ul>
</template>

<script>
    export default {
        name:"DetailS",
        mounted(){
            console.log(this.$route);
        }
    }
</script>

<style>

</style>
Message.vue
<template>
    <div>
        <ul>
            <li v-for="m in messageList" :key="m.id">
                <!-- 跳转路由并携带query参数,to的字符串写法 -->
                <!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp; -->

                <!-- 跳转路由并携带query参数,to的字符串写法 -->
                <router-link :to="{
                    path:'/home/message/detail',
                    query:{
                        id:m.id,
                        title:m.title
                    }
                }">
                    {{m.title}}
                </router-link>
            </li>
        </ul>
        <hr>
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name:"MessageS",
        data(){
            return {
                messageList:[
                    {id:'001',title:'消息001'},
                    {id:'002',title:'消息002'},
                    {id:'003',title:'消息003'},
                ]
            }
        }
    }
</script>


router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
// 创建一个路由器
const router = new VueRouter({
    routes:[
        {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:"message",
                    component:Message,
                    children:[
                        {
                            path:'detail',
                            component:Detail
                        }
                    ]
                },
                {
                    path:"news",
                    component:News,
                }
            ]
        },
    ]
})


export default router

6、命名路由

  1. 作用:可以简化路由的跳转。

  2. 如何使用

    1. 给路由命名:

      {
        path:'/demo',
        component:Demo,
        children:[
            {
                path:'test',
                component:Test,
                children:[
                    {
                            name:'hello' //给路由命名
                        path:'welcome',
                        component:Hello,
                    }
                ]
            }
        ]
      }
      
    2. 简化跳转:

      <!--简化前,需要写完整的路径 -->
      <router-link to="/demo/test/welcome">跳转</router-link>
      
      <!--简化后,直接通过名字跳转 -->
      <router-link :to="{name:'hello'}">跳转</router-link>
      
      <!--简化写法配合传递参数 -->
      <router-link 
        :to="{
            name:'hello',
            query:{
               id:666,
                  title:'你好'
            }
        }"
      >跳转</router-link>
      

7、params参数

  1. 配置路由,声明接收params参数

    {
     path:'/home',
     component:Home,
     children:[
         {
             path:'news',
             component:News
         },
         {
             component:Message,
             children:[
                 {
                     name:'xiangqing',
                     path:'detail/:id/:title', //使用占位符声明接收params参数
                     component:Detail
                 }
             ]
         }
     ]
    }
    
  2. 传递参数

    <!-- 跳转并携带params参数,to的字符串写法 -->
    <router-link :to="/home/message/detail/666/你好">跳转</router-link>
                 
    <!-- 跳转并携带params参数,to的对象写法 -->
    <router-link 
     :to="{
         name:'xiangqing',
         params:{
            id:666,
                title:'你好'
         }
     }"
    >跳转</router-link>
    

    特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!

  3. 接收参数:

    $route.params.id
    $route.params.title
    

8、路由的props配置

作用:让路由组件更方便的收到参数

{

  name:'xiangqing',

  path:'detail/:id',

  component:Detail,



  *//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件*

  *// props:{a:900}*



  *//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件*

  *// props:true*

  

  *//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件*

  props(route){

​    return {

​      id:route.query.id,

​      title:route.query.title

​    }

  }

}

源码

index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
// 创建一个路由器
const router = new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[
                {
                    // name:'xiaoxi',
                    path:"message",
                    component:Message,
                    children:[
                        {
                            name:'xiangqing',
                            // path:'detail/:id/:title',
                            path:'detail',
                            component:Detail,
                            // props的第一种写法,值为对象,该对象的所有key-value都会以props的形式传给Detail组件
                            /* props:{
                                a:1,
                                b:"hello"
                            } */

                            // props的第二种写法,值为布尔值,若为true则会把该路由组件收到的所有params参数,以props的形式传给detail组件
                            // props:true

                            // props的第三种写法,值为函数
                            /* props($route){
                                return {
                                    id:$route.query.id,
                                    title:$route.query.title
                                }
                            } */
                            props({query:{id,title}}){
                                return {id,title}
                            }
                        }
                    ]
                },
                {
                    path:"news",
                    component:News,
                }
            ]
        },
    ]
})


export default router
Detail.vue
<template>
    <ul>
        <!-- <li>消息编号:{{$route.query.id}}</li>
        <li>消息标题:{{$route.query.title}}</li> -->
        <!-- <li>消息编号:{{$route.params.id}}</li>
        <li>消息标题:{{$route.params.title}}</li> -->
        <li>消息编号:{{id}}</li>
        <li>消息标题:{{title}}</li>
        <!-- <li>a:{{a}}</li>
        <li>b:{{b}}</li> -->
    </ul>
</template>

<script>
    export default {
        name:"DetailS",
        // props:['a','b'],
        props:['id','title'],
        mounted(){
            console.log(this.$route);
        }
    }
</script>

<style>

</style>
Message.vue
<template>
    <div>
        <ul>
            <li v-for="m in messageList" :key="m.id">
                <!-- 跳转路由并携带params参数,to的字符串写法 -->
                <!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp; -->


                <!-- 跳转路由并携带params参数,to的字符串写法 -->
                <router-link :to="{
                    // path:'/home/message/detail',
                    name:'xiangqing',
                    /* params:{
                        id:m.id,
                        title:m.title
                    } */
                    query:{
                        id:m.id,
                        title:m.title
                    }
                }">
                    {{m.title}}
                </router-link>
            </li>
        </ul>
        <hr>
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name:"MessageS",
        data(){
            return {
                messageList:[
                    {id:'001',title:'消息001'},
                    {id:'002',title:'消息002'},
                    {id:'003',title:'消息003'},
                ]
            }
        }
    }
</script>


9、<router-link>的replace属性

1、作用:控制路由跳转时操作浏览器历史记录的模式

2、浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候默认为push

2、如何开启replace模式:<router-link replace .......>News</router-link>

10、编程式路由导航

1、作用:不借助<router-link> 实现路由跳转,让路由跳转更加灵活

2、具体编码:

    //$router的两个API
   this.$router.push({
    name:'xiangqing',
        params:{
            id:xxx,
            title:xxx
        }
   })
   
   this.$router.replace({
    name:'xiangqing',
        params:{
            id:xxx,
            title:xxx
        }
   })
   this.$router.forward() //前进
   this.$router.back() //后退
   this.$router.go() //可前进也可后退

image-20221111115707600

源码

banner.vue
<template>
    <div class="col-xs-offset-2 col-xs-8">
        <div class="page-header">
            <h2>Vue Router Demo</h2>
            <button @click="back">后退</button>
            <button @click="forward">前进</button>
            <button @click="go">go前进三步</button>
        </div>
    </div>
</template>

<script>
    export default {
        name:"BannerS",
        methods:{
            back(){
                // console.log(this.$router);
                this.$router.back()
            },
            forward(){
                // console.log(this.$router);
                this.$router.forward()
            },
            go(){
                // console.log(this.$router);
                this.$router.go(3)
            },
        }
    }
</script>

Message.vue
<template>
    <div>
        <ul>
            <li v-for="m in messageList" :key="m.id">
                <!-- 跳转路由并携带params参数,to的字符串写法 -->
                <!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp; -->


                <!-- 跳转路由并携带params参数,to的字符串写法 -->
                <router-link :to="{
                    // path:'/home/message/detail',
                    name:'xiangqing',
                    /* params:{
                        id:m.id,
                        title:m.title
                    } */
                    query:{
                        id:m.id,
                        title:m.title
                    }
                }">
                    {{m.title}}
                </router-link>
                <button @click="pushShow(m)">push查看</button>
                <button @click="replaceShow(m)">replace查看</button>
            </li>
        </ul>
        <hr>
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name:"MessageS",
        data(){
            return {
                messageList:[
                    {id:'001',title:'消息001'},
                    {id:'002',title:'消息002'},
                    {id:'003',title:'消息003'},
                ]
            }
        },
        methods:{
            pushShow(m){
                // console.log(this.$router);
                this.$router.push({
                    name:'xiangqing',
                    query:{
                        id:m.id,
                        title:m.title
                    }
                })
            },
            replaceShow(m){
                // console.log(this.$router);
                this.$router.replace({
                    name:'xiangqing',
                    query:{
                        id:m.id,
                        title:m.title
                    }
                })
            }
        },
        
    }
</script>


11、缓存路由组件

1、作用:让不展示的路由组件保持挂载,不被销毁。

2、 具体编码:(include填写组件名)

			<!-- 缓存多个路由组件 -->
            <!-- <keep-alive :include="['NewS','Message']">
                <router-view></router-view>
            </keep-alive> -->
            
            <!-- 缓存一个路由组件 -->
            <keep-alive include="NewS">
                <router-view></router-view>
            </keep-alive>

12、两个新的生命周期

1、作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。

2、 具体名字:

```activated```路由组件被激活时触发。

deactivated路由组件失活时触发。

13、路由守卫

  1. 作用:对路由进行权限控制

  2. 分类:全局守卫、独享守卫、组件内守卫

  3. 全局守卫:

    //全局前置守卫:初始化时执行、每次路由切换前执行
    router.beforeEach((to,from,next)=>{
    	console.log('beforeEach',to,from)
    	if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
    		if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则
    			next() //放行
    		}else{
    			alert('暂无权限查看')
    			// next({name:'guanyu'})
    		}
    	}else{
    		next() //放行
    	}
    })
    
    //全局后置守卫:初始化时执行、每次路由切换后执行
    router.afterEach((to,from)=>{
    	console.log('afterEach',to,from)
    	if(to.meta.title){ 
    		document.title = to.meta.title //修改网页的title
    	}else{
    		document.title = 'vue_test'
    	}
    })
    
  4. 独享守卫:

    beforeEnter(to,from,next){
    	console.log('beforeEnter',to,from)
    	if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
    		if(localStorage.getItem('school') === 'atguigu'){
    			next()
    		}else{
    			alert('暂无权限查看')
    			// next({name:'guanyu'})
    		}
    	}else{
    		next()
    	}
    }
    
  5. 组件内守卫:

    //进入守卫:通过路由规则,进入该组件时被调用
    beforeRouteEnter (to, from, next) {
    },
    //离开守卫:通过路由规则,离开该组件时被调用
    beforeRouteLeave (to, from, next) {
    }
    

源码

router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
// 创建一个路由器
const router = new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About,
            meta:{isAuth:true,title:'关于'}
        },
        {
            name:"zhuye",
            path:'/home',
            component:Home,
            meta:{title:'主页'},
            children:[
                {
                    name:'xiaoxi',
                    path:"message",
                    component:Message,
                    meta:{isAuth:true,title:'消息'},
                    children:[
                        {
                            name:'xiangqing',
                            // path:'detail/:id/:title',
                            path:'detail',
                            component:Detail,
                            meta:{isAuth:true,title:'详情'},                
                            // props的第一种写法,值为对象,该对象的所有key-value都会以props的形式传给Detail组件
                            /* props:{
                                a:1,
                                b:"hello"
                            } */

                            // props的第二种写法,值为布尔值,若为true则会把该路由组件收到的所有params参数,以props的形式传给detail组件
                            // props:true

                            // props的第三种写法,值为函数
                            /* props($route){
                                return {
                                    id:$route.query.id,
                                    title:$route.query.title
                                }
                            } */
                            props({query:{id,title}}){
                                return {id,title}
                            }
                        }
                    ]
                },
                {
                    name:'xinwen',
                    path:"news",
                    component:News,
                    meta:{isAuth:true,title:'新闻'},
                    /* beforeEnter:(to,from,next)=>{
                        console.log('独享路由守卫',to,from,next)
                        if(to.meta.isAuth){
                            if(localStorage.getItem('school')==='atguigu'){
                                next()
                            }else{
                                alert('学校名不对,没有权限查看')
                            }
                        }else{
                            next()
                        }
                    } */
                }
            ]
        },
    ]
})

// 全局前置路由守卫----初始化时被调用,还有每次路由切换之前被调用
/* router.beforeEach((to,from,next)=>{
    console.log('前置路由守卫',to,from,next)
    // if(to.path==='/home/news' || to.path==='/home/message'){
    // if(to.name==='xinwen' || to.name==='xiaoxi'){
        if(to.meta.isAuth){
        if(localStorage.getItem('school')==='atguigu'){
            // document.title=to.meta.title || '尚硅谷系统'
            next()
        }else{
            alert('学校名不对,没有权限查看')
        }
    }else{
        // document.title=to.meta.title || '尚硅谷系统'   
        next()
    }
}) */




// 全局后置路由守卫----初始化时被调用,还有每次路由切换之后被调用
/* router.afterEach((to,from)=>{
    console.log('后置路由守卫',to,from)
    document.title=to.meta.title || '尚硅谷系统'   
    
}) */




export default router
About.vue
<template>
    <h2>我是About的内容</h2>
</template>

<script>
    export default {
        name:"AboutMe",
        /* beforeDestroy() {
            console.log("about即将销毁了")
        }, */
        /* mounted(){
            console.log("about挂载好了",this);
            window.aboutRoute = this.$route
            window.aboutRouter = this.$router
        } */

        // 通过路由规则,进入该组件时被调用
        beforeRouteEnter(to,from,next){
            console.log('About---beforeRouteEnter',to,from,next)
            if(to.meta.isAuth){
                if(localStorage.getItem('school')==='atguigu'){
                    next()
                }else{
                    alert('学校名不对,没有权限查看')
                }
            }else{
                next()
            }
        },
        // 通过路由规则,离开该组件被调用
        beforeRouteLeave(to,from,next){
            console.log('About---beforeRouteLeave',to,from,next)
            next()
        }
    }
</script>


14.路由器的两种工作模式

  1. 对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值。
  2. hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。
  3. hash模式:
    1. 地址中永远带着#号,不美观 。
    2. 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
    3. 兼容性较好。
  4. history模式:
    1. 地址干净,美观 。
    2. 兼容性和hash模式相比略差。
    3. 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。

1、修改路由器工作模式(mode配置项)

// 创建一个路由器
const router = new VueRouter({
    mode:'history',
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About,
            meta:{isAuth:true,title:'关于'}
        },

2、将vue项目打包成静态资源

npm run build

3、使用node.js写一台简易服务器

  1. 初始化项目

    npm init

  2. 安装express框架

    npm i express

  3. 新建server.js编写服务器逻辑代码

    const express = require('express')
    const app = express()
    app.use(express.static(__dirname+'/static'))
    app.get('/person',(req,res)=>{
        res.send({
            name:'tom',
            age:18
        })
    })
    
    app.listen(5005,(err)=>{
        if(!err) console.log('服务器启动成功了!')
    })
    
  4. 安装history中间件解决,404问题

    npm i connect-history-api-fallback

  5. 引入并使用

    const express = require('express')
    const history = require('connect-history-api-fallback')
    
    const app = express()
    
    //以下这行代码必须在使用静态资源之前
    app.use(history())
    app.use(express.static(__dirname+'/static'))
    
    app.get('/person',(req,res)=>{
        res.send({
            name:'tom',
            age:18
        })
    })
    
    app.listen(5005,(err)=>{
        if(!err) console.log('服务器启动成功了!')
    })
    

47、Vue----UI组件库

1、移动端常用 UI 组件库

  1. Vant youzan.github.io/vant
  2. Cube UI didi.github.io/cube-ui
  3. Mint UI mint-ui.github.io

2、PC端常用UI组件库

  1. Element UI element.eleme.cn
  2. IView UI www.iviewui.co

本文作者:_xiaolin

本文链接:https://www.cnblogs.com/SilverStar/p/17415640.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   _xiaolin  阅读(0)  评论(0编辑  收藏  举报  
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起