vue笔记

Vue核心

Vue简介

介绍 — Vue.js (vuejs.org)

Vue是什么?

一套用于构建用户界面渐进式js框架

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

简单应用:只需要一个轻量小巧的核心库

复杂应用:可以引用各式各样的Vue插件

谁开发的

尤雨溪

Vue的特点

  1. 采用组件化模式,提高代码复用率,且让代码更好维护。
  2. 声明式编码,让编码人员无需直接操作DOM,提高开发效率。
  3. 使用虚拟机DOM+优秀的Diff算法,尽量复用DOM节点

学习Vue之前要掌握的js基础知识

初识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>
    <script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <h1>Hello,{{name}}{{id}}</h1>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: {//data中用于存储数据,数据供el所指定的容器去使用,值
                name: '郝佳瑶',
                id: '卧槽'
            }
        })
    </script>
</body>
</html>

模板语法

 <!-- 准备好一个容器 -->
    <div id="root">
        <h1>Hello,{{name}}{{id}}</h1>
        <h1>指令语法</h1>
        <a :href="url">百度</a>
        <a v-bind:href="url">百度</a>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: {//data中用于存储数据,数据供el所指定的容器去使用,值
                name: '郝佳瑶',
                id: '卧槽',
                url: "https://www.baidu.com/"
            }
        })
    </script>

数据绑定:v-bind:

<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>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: "#root",
            data: {
                name: "郝佳瑶"
            }
        })
    </script>
</body>

单项数据绑定

  1. 语法:v-bind:href ="xxx" 或简写为 :href ="xxx"
  2. 特点:数据不仅能从 data 流向页面,还能从页面流向 data

双向数据绑定

  1. 语法:v-mode:value="xxx" 或简写为 v-model="xxx"
  2. 特点:数据不仅能从 data 流向页面,还能从页面流向 data

el和fata的两种写法

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <h1>你好{{name}}</h1>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        const v = new Vue({
            //el: "#root",//第一种写法
            // data: {
            //     name: "郝佳瑶"
            // }
            data(){
                return{
                    name: "郝佳瑶"
                }
            }
        })
        console.log(v)
        v.$mount('#root')//第二种写法(挂载)
    </script>
</body>

MVVM模型

  1. M:模型(Model):对应data中的数据
  2. V:视图(View):模板
  3. VM:视图模型(ViewModel):Vue实例对象

事件处理

数据代理

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        let num = 20
        let person = {
            name: '张三',
            sex: '男',
        }

        Object.defineProperty(person,'age',{
            //value: 18,
            //enumerable: true,//控制属性是否可以枚举,默认false
            //writable: true,//控制属性可以被修改,默认false
            //configurable: true,//控制属性是否可以删除,默认false
            get(){
                console.log('有人读取了age属性')
                return num;
            },//读取person的age属性,get函数就会被调用,且返回age的值
            set(value){
                console.log('有人修改了age属性,且值是',value)
                num = value
            }//修改person的age属性,set函数就会被调用,且收到修改的具体值
        })
        console.log(person)
    </script>
</body>

image-20220329105144641

事件绑定

<div id="root">
        <h2>我是大聪明{{name}}</h2>
        <button v-on:click="showInfo(66,$event)">点我提示信息(传参数)</button>
        <button @click="showInfo1">点我提示信息(不传参数)</button>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        const vm= new Vue({
            el: '#root',
            data: {
                name: '郝佳瑶'
            },
            methods: {
                showInfo(number,event) {
                    console.log(number),
                    console.log(event),
                    alert('我确实是大聪明')
                },
                showInfo1(event) {
                    console.log(event.target.innerText),
                    console.log(this)//此处的this是vm
                }
            }
        })
    </script>

Vue中的事件修饰符

  1. prevent:阻止默认事件(常用)
  2. stop:阻止事件冒泡(常用)
  3. once:事件只触发一次(常用)
  4. capture:使用事件的捕获模式
  5. self:只有event.target是当前操作的元素时才触发事件
  6. passive:事件默认行为立即执行,无需等待事件回调执行完毕
<body>
<!-- 
1. prevent:阻止默认事件(常用)
2. stop:阻止事件冒泡(常用)
3. once:事件只触发一次(常用)
4. capture:使用事件的捕获模式
5. self:只有event.target是当前操作的元素时才触发事件
6. passive:事件默认行为立即执行,无需等待事件回调执行完毕
 -->
    <div id="root">
        <h2>{{name}}</h2>
        <!-- 阻止默认事件 -->
        <a href="http://www.baidu.com" @click.prevent="showInfo">阻止默认事件</a>
        <!-- 阻止事件冒泡 -->
        <div class="demol" @click="showInfo">
            <button @click.stop="showInfo">阻止事件冒泡</button>
        </div>
        <!-- 事件只触发一次 -->
        <button @click.once="showInfo">事件只触发一次</button>
    </div>
</body>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root',
            data: {
                name: '郝佳瑶'
            },
            methods: {
                showInfo(){
                    alert('老子真可爱')
                }
            }
            
        })
    </script>

键盘绑定

<body>
    <div id="root">
        <h2>我是大聪明{{name}}</h2>
        <input type="text" placeholder="按下回车键提示输入" @keyup="showInfo">
        <input type="text" placeholder="按下回车键提示输入" @keyup.enter="showInfo1">
    </div>
</body>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root',
            data: {
                name: '郝佳瑶'
            },
            methods: {
                showInfo(e) {
                    if(e.keyCode !== 13)return
                    console.log(e.target.value)
                },
                showInfo1(e) {
                    console.log(e.target.value)
                }
            }
        })
    </script>
  1. Vue常用的案按键别名:

回车 enter

删除 delete

退出 esc

空格 space

换行 tab 特殊配合keydown使用

上下左右 up down left right

  1. Vue未提供别名的按键,可以使用按键原始的key值去绑定,但是要注意转为kebab-case(短横线命名)
  2. 系统修饰键(用法特殊):ctrl alt shift meta

配合keyup使用:按下修饰键的同时,再按下其他键,然后释放其他键,事件才会触发。

配合keydown使用:正常触发事件。

  1. 可以使用keyCode去指定具体的按键(不推荐)
  2. Vue.config.keyCode.自定义键名 = 键码 可以定制按键别名

计算属性

姓名案例

<body>
    <div id="root">
        姓:<input type="text" v-model="firstName"><br>
        名:<input type="text" v-model="lasttName"><br>
        姓名1:<span>{{firstName.slice(0,3)+'-'+lasttName}}</span><br>
        姓名2:<span>{{fullName()}}</span><br>
        姓名2:<span>{{fullName1}}</span>
    </div>
</body>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        const vm = new Vue({
            el: '#root',
            data: {
                firstName: '张',
                lasttName: '三'
            },
            methods: {
                fullName(){
                    return this.firstName+'-'+this.lasttName
                }
            },
            computed: {
                fullName1: {
                    //Get的作用?但有人读取fullName,get就会被调用,且返回fullName的值
                    //Get什么时候调用?1.初次读取fullName时。 2.所依赖的数据发生变化时。
                    get(){
                        console.log('Get被调用了')
                        console.log(this)//这里的this是vm
                        return this.firstName+'-'+this.lasttName
                    }
                    set(value){
                        console.log('set',value)
                        const arr= value.split('-')
                        this.firstName = arr[0]
                        this.lasttName = arr[1]
                    } 
                }
            }
            
        })
    </script>

姓名案例_计算属性简写

只get不set可以简写

computed: {
                fullName1() {
                    console.log('get被调用了')
                    return this.firstName+'-'+this.lasttName
                }
            }

监视属性

天气案例

<body>
    <div id="root">
       <h2>今天天气很{{isHot ? '炎热':'凉爽'}}</h2>
       <h2>今天天气很{{info}},{{x}}</h2>
       <button @click="change">切换天气</button>
       <!-- 做事简单可以这样写,事情多不建议这样写 -->
       <button @click="isHot = !isHot;x++">切换天气</button>
    </div>
</body>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root',
            data: {
                isHot: true,
                x: 1
            },
            computed: {
                info(){
                    return this.isHot ? '炎热':'凉爽'
                }
            },
            methods: {
                change(){
                    this.isHot = !this.isHot
                }
            },
        })
    </script>

监视属性

<body>
    <!-- 监视属性watch:
          1.当被监视属性变化时,回调函数自动调用,进行相关操作
          2.监视的属性必须存在,才能进行监视
          3.监视的两种写法:
             1>.new Vue时传入watch属性
             2>.通过vm.$watch监视
    -->
    <div id="root">
       <h2>今天天气很{{isHot ? '炎热':'凉爽'}}</h2>
       <h2>今天天气很{{info}}</h2>
       <button @click="change">切换天气</button>
    </div>
</body>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        const vm = new Vue({
            el: '#root',
            data: {
                isHot: true,
            },
            computed: {
                info(){
                    return this.isHot ? '炎热':'凉爽'
                }
            },
            methods: {
                change(){
                    this.isHot = !this.isHot
                }
            },
            // watch: {
            //     isHot: {
            //         immediate: true,//初始化时让handler调用一下
            //         //handler什么时候调用?当isHot发生变化时
            //         handler(newValue,oldValue){
            //             console.log('isHot被改了',newValue,oldValue)
            //         }
            //     },
            //     info: {
            //         immediate: true,//初始化时让handler调用一下
            //         //handler什么时候调用?当isHot发生变化时
            //         handler(newValue,oldValue){
            //             console.log('info被改了',newValue,oldValue)
            //         }
            //     }
            // }
        })
        vm.$watch('isHot',{
            immediate:true,
            handler(newValue,oldValue){
                console.log('isHot被改了',newValue,oldValue)
            }
        })
    </script>

深度监视

<body>
    <!-- 
        深度监视:
          1.Vue中的watch默认不监视对象内部值的改变
          2.配置deep:true可以监测对象内部值的改变
        备注:
          1.Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以
          2.使用洼田崇时根据数据的具体结构,决定是否采用深度监视
     -->
    <div id="root">
       <h2>今天天气很{{isHot ? '炎热':'凉爽'}}</h2>
       <h2>今天天气很{{info}}</h2>
       <button @click="change">切换天气</button>
       <h2>a的值是{{num.a}}</h2>
       <button @click="num.a++">a加一</button>
       <h2>b的值是{{num.b}}</h2>
       <button @click="num.b++">b加一</button>
    </div>
</body>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        const vm = new Vue({
            el: '#root',
            data: {
                isHot: true,
                num: {
                    a: 1,
                    b: 1
                }
            },
            computed: {
                info(){
                    return this.isHot ? '炎热':'凉爽'
                }
            },
            methods: {
                change(){
                    this.isHot = !this.isHot
                }
            },
            watch: {
                isHot: {
                    //immediate: true,//初始化时让handler调用一下
                    //handler什么时候调用?当isHot发生变化时
                    handler(newValue,oldValue){
                        console.log('isHot被改了',newValue,oldValue)
                    }
                },
                //监视多级结构中某个属性的变化
                'num.a':{
                    handler(){
                        console.log('a被改变了')
                    }
                },
                //监视多级结构中所有属性的变化
                num: {
                    deep: true,//深度监视
                    handler(){
                        console.log('num被改变了')
                    }
                }
            }
        })
    </script>

简写

<body>
    <div id="root">
        <h2>今天天气很{{isHot ? '炎热':'凉爽'}}</h2>
        <h2>今天天气很{{info}}</h2>
        <button @click="change">切换天气</button>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false //设置为 false 以阻止 vue 在启动时生成生产提示。
    const vm = new Vue({
        el: '#root',
        data: {
            isHot: true,
        },
        computed: {
            info() {
                return this.isHot ? '炎热' : '凉爽'
            }
        },
        methods: {
            change() {
                this.isHot = !this.isHot
            }
        },
        watch: {
            //正常写法
            // isHot: {
            //     //immediate: true,//初始化时让handler调用一下
            //     //deep: true,//深度监视
            //     //handler什么时候调用?当isHot发生变化时
            //     handler(newValue, oldValue) {
            //         console.log('isHot被改了', newValue, oldValue)
            //     }
            // },
            //简写
            // 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>

computed和watch的区别

  1. computed能完成的功能,watch都可以完成
  2. watch能完成的功能,computed不一定能完成,例如:watch可以进行异步操作。

备注

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

绑定样式

class绑定

  1. 表达式是字符串: 'classA' 适用于:类名不确定,要动态获取
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <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 dashed rgb(2, 197, 2);
      background-color: gray;
    }

    .normal {
      background-color: skyblue;
    }

  </style>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/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

  const vm = new Vue({
    el: '#root',
    data: {
      name: 'YK菌',
      mood: 'normal'
    },
    methods: {
      changeMood() {
        const arr = ['happy', 'sad', 'normal']
        const index = Math.floor(Math.random() * 3)
        this.mood = arr[index]
      }
    },
  })
</script>

</html>

  1. 表达式是数组: ['classA', 'classB'] 适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>绑定样式</title>
  <style>
    .basic {
      width: 400px;
      height: 100px;
      border: 1px solid black;
    }

    .yk1 {
      background-color: yellowgreen;
    }

    .yk2 {
      font-size: 30px;
      text-shadow: 2px 2px 10px red;
    }

    .yk3 {
      border-radius: 20px;
    }
  </style>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.js"></script>
</head>

<body>

  <!-- 准备好一个容器-->
  <div id="root">

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

  </div>
</body>

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

  const vm = new Vue({
    el: '#root',
    data: {
      name: 'YK菌',
      classArr: ['yk1', 'yk2', 'yk3']
    },
  })
</script>

</html>

  1. 表达式是对象: {classA:isA, classB: isB} 适用于:要绑定多个样式,个数不确定,名字也不确定
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>绑定样式</title>
  <style>
    .basic {
      width: 400px;
      height: 100px;
      border: 1px solid black;
    }

    .yk1 {
      background-color: yellowgreen;
    }

    .yk2 {
      font-size: 30px;
      text-shadow: 2px 2px 10px red;
    }

    .yk3 {
      border-radius: 20px;
    }
  </style>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.js"></script>
</head>

<body>

  <!-- 准备好一个容器-->
  <div id="root">

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

  </div>
</body>

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

  const vm = new Vue({
    el: '#root',
    data: {
      name: 'YK菌',
      classObj: {
        yk1: true,
        yk2: false,
        yk3: true
      }
    }
  })
</script>

</html>

style绑定

:style="{fontSize: xxx}"其中xxx是动态值。
:style="[a,b]"其中a、b是样式对象。

对象

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>绑定样式</title>
  <style>
    .basic {
      width: 400px;
      height: 100px;
      border: 1px solid black;
    }
  </style>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.js"></script>
</head>

<body>

  <!-- 准备好一个容器-->
  <div id="root">

    <!-- 绑定style样式--对象写法 -->
    <div class="basic" :style="styleObj, styleObj2">{{name}}</div>

  </div>
</body>

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

  const vm = new Vue({
    el: '#root',
    data: {
      name: 'YK菌',
      styleObj: {
        fontSize: '40px',
        color: 'red',
      },
      styleObj2: {
        backgroundColor: 'orange'
      },
    },
  })
</script>

</html>

数组

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>绑定样式</title>
  <style>
    .basic {
      width: 400px;
      height: 100px;
      border: 1px solid black;
    }
  </style>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.js"></script>
</head>

<body>

  <!-- 准备好一个容器-->
  <div id="root">

    <!-- 绑定style样式--数组写法 -->
    <div class="basic" :style="styleArr">{{name}}</div>

  </div>
</body>

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

  const vm = new Vue({
    el: '#root',
    data: {
      name: 'YK菌',
      styleArr: [{
          fontSize: '40px',
          color: 'blue',
        },
        {
          backgroundColor: 'gray'
        }
      ]
    },
  })
</script>

</html>

条件渲染

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <!-- 用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> -->
        <h2>当前的值是{{a}}</h2>
        <button @click="a++">点我</button>
        <!-- <div v-show="a === 1">hongyuhao1</div>
        <div v-show="a === 2">hongyuhao2</div>
        <div v-show="a === 3">hongyuhao3</div> -->
        <div v-if="a === 1">hongyuhao1</div>
        <div v-else-if="a === 2">hongyuhao2</div>
        <div v-else-if="a === 3">hongyuhao3</div> 
        <div v-else="a === 3">haojiayao</div>
        <!-- v-if 与 template -->
        <template v-if="a === 1">
            <h2>你好</h2>
            <h2>郝佳瑶</h2>
            <h2>西安</h2>
        </template>
        
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: {//data中用于存储数据,数据供el所指定的容器去使用,值
                name: '郝佳瑶',
                a: 0
            }
        })
    </script>
</body>

image-20220401113755692

列表渲染

基本列表

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <!-- 遍历数组 -->
        <h2>人员列表</h2>
        <ul>
            <!-- <li v-for="p in persons" :key="p.id">{{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,key) in car" ::key="key">
                {{key}}-{{value}}
            </li>
        </ul>
        <!-- 遍历字符串 -->
        <h2>遍历字符串</h2>
        <ul>
            <li v-for="(char,index) in str" ::key="index">
                {{index}}-{{char}}
            </li>
        </ul>
        <!-- 遍历指定次数 -->
        <ul>
            <li v-for="(number,index) in 5" ::key="index">
                {{index}}-{{number}}
            </li>
        </ul>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: {//data中用于存储数据,数据供el所指定的容器去使用,值
                persons: [
                    {
                        id: '001',
                        name: '张三',
                        age: 18
                    },
                    {
                        id: '002',
                        name: '张si',
                        age: 20
                    },
                    {
                        id: '003',
                        name: '张wo',
                        age: 23
                    }
                ],
                car: {
                    name: '宝马',
                    price: '70w',
                    color: 'red'
                },
                str: 'hello'
            }
        })
    </script>
</body>

列表过滤watch实现

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <!-- 遍历数组 -->
        <h2>人员列表</h2>
        <input type="text" placeholder="请输入名字" v-model="keyWord">
        <ul>
            <!-- <li v-for="p in persons" :key="p.id">{{p.id}}-{{p.name}}-{{p.age}}</li> -->
            <li v-for="(p,index) in filPersons" ::key="index">
                {{p.name}}-{{p.age}}
            </li>
        </ul>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: {//data中用于存储数据,数据供el所指定的容器去使用,值
                keyWord:'',
                persons: [
                    {
                        id: '001',
                        name: '周冬雨',
                        age: 18
                    },
                    {
                        id: '002',
                        name: '马冬梅',
                        age: 20
                    },
                    {
                        id: '003',
                        name: '周杰伦',
                        age: 23
                    },
                    {
                        id: '004',
                        name: '徐伦',
                        age: 43
                    }
                ],
                filPersons: [],
            },
            watch: {
                keyWord: {
                    immediate: true,
                    handler(val){
                        this.filPersons = this.persons.filter((p)=>{
                            return p.name.indexOf(val) !== -1
                        })
                    }
                }
            },
        })
    </script>
</body>

列表过滤conputed实现

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <!-- 遍历数组 -->
        <h2>人员列表</h2>
        <input type="text" placeholder="请输入名字" v-model="keyWord">
        <ul>
            <!-- <li v-for="p in persons" :key="p.id">{{p.id}}-{{p.name}}-{{p.age}}</li> -->
            <li v-for="(p,index) in filPersons" ::key="index">
                {{p.name}}-{{p.age}}
            </li>
        </ul>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: {//data中用于存储数据,数据供el所指定的容器去使用,值
                keyWord:'',
                persons: [
                    {
                        id: '001',
                        name: '周冬雨',
                        age: 18
                    },
                    {
                        id: '002',
                        name: '马冬梅',
                        age: 20
                    },
                    {
                        id: '003',
                        name: '周杰伦',
                        age: 23
                    },
                    {
                        id: '004',
                        name: '徐伦',
                        age: 43
                    }
                ],
            },
            watch: {
                keyWord: {
                    immediate: true,
                    handler(val){
                        this.filPersons = this.persons.filter((p)=>{
                            return p.name.indexOf(val) !== -1
                        })
                    }
                }
            },
            // computed: {
            //     filPersons: {
            //         get(){
            //         return this.persons.filter((p)=>{
            //             return p.name.indexOf(this.keyWord) != -1
            //         })
            //     }
            //     }
            // }
            // 简写
            computed: {
                filPersons(){
                    return this.persons.filter((p)=>{
                        return p.name.indexOf(this.keyWord) != -1
                    })
                }
            }
        })
    </script>

列表排序

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <!-- 遍历数组 -->
        <h2>人员列表</h2>
        <input type="text" placeholder="请输入名字" v-model="keyWord">
        <ul>
            <!-- <li v-for="p in persons" :key="p.id">{{p.id}}-{{p.name}}-{{p.age}}</li> -->
            <li v-for="(p,index) in filPersons" :key="index">
                {{p.name}}-{{p.age}}
            </li>
        </ul>
        <button @click="sortType = 2">年龄升序</button>
        <button @click="sortType = 1">年龄降序</button>
        <button @click="sortType = 0">还原顺序</button>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false //设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: { //data中用于存储数据,数据供el所指定的容器去使用,值
                sortType: '0',
                keyWord: '',
                persons: [{
                        id: '001',
                        name: '周冬雨',
                        age: 36
                    },
                    {
                        id: '002',
                        name: '马冬梅',
                        age: 20
                    },
                    {
                        id: '003',
                        name: '周杰伦',
                        age: 18
                    },
                    {
                        id: '004',
                        name: '徐伦',
                        age: 43
                    }
                ],
            },
            // computed: {
            //     filPersons: {
            //         get(){
            //         return this.persons.filter((p)=>{
            //             return p.name.indexOf(this.keyWord) != -1
            //         })
            //     }
            //     }
            // }
            // 简写
            computed: {
                filPersons() {
                    const arr = this.persons.filter((p) => {
                        return p.name.indexOf(this.keyWord) != -1
                    })
                    //判断一下是否需要排序
                    if (this.sortType) {
                        arr.sort((p1, p2) => {
                            return this.sortType === 1 ? p2.age - p1.age : p1.age - p2.age
                        })
                    }
                    return arr

                }
            }
        })
    </script>
</body>

更新时的一个问题

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <!-- 遍历数组 -->
        <h2>人员列表</h2>
        <Button @click="updateMei">更新马冬梅的信息</Button>
        <ul>
            <!-- <li v-for="p in persons" :key="p.id">{{p.id}}-{{p.name}}-{{p.age}}</li> -->
            <li v-for="(p,index) in persons" :key="p.id">
                {{p.name}}-{{p.age}}
            </li>
        </ul>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: {//data中用于存储数据,数据供el所指定的容器去使用,值
                persons: [
                {
                        id: '001',
                        name: '周冬雨',
                        age: 18
                    },
                    {
                        id: '002',
                        name: '马冬梅',
                        age: 20
                    },
                    {
                        id: '003',
                        name: '周杰伦',
                        age: 23
                    },
                    {
                        id: '004',
                        name: '徐伦',
                        age: 43
                    }
                ],
            },
            methods: {
                updateMei(){
                    //this.persons[0].name = '马老师',//奏效
                    //this.persons[0].age = '60'//奏效
                    this.persons[0] = {id: '001',name: '马老师',age: '60'}//不奏效
                }
            },
        })
    </script>
</body>

Vue监视数据原理

  1. vue会监视data中所有层次的数据。

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

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

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

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

  1. 在Vue修改数组中的某个元素一定要用如下方法:
    (1). 使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()
    (2). Vue.set() 或 vm.$set()

    特别注意:Vue.set() 和 vm.$set() 不能给vm 或 vm的根数据对象 添加属性!!!

总结

<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/>
			<button @click="removeSmoke">过滤掉爱好中的抽烟</button> <br/>
			<h3>姓名:{{student.name}}</h3>
			<h3>年龄:{{student.age}}</h3>
			<h3 v-if="student.sex">性别:{{student.sex}}</h3>
			<h3>爱好:</h3>
			<ul>
				<li v-for="(h,index) in student.hobby" :key="index">
					{{h}}
				</li>
			</ul>
			<h3>朋友们:</h3>
			<ul>
				<li v-for="(f,index) in student.friends" :key="index">
					{{f.name}}--{{f.age}}
				</li>
			</ul>
		</div>
	</body>

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

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

表单数据收集

使用v-model(双向数据绑定)自动收集数据

  1. text/textarea
  2. checkbox
  3. radio
  4. select

,则v-model收集的是value值,用户输入的就是value值。
,则v-model收集的是value值,且要给标签配置value值。

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

  2. 配置input的value属性:
    (1). v-model的初始值是非数组,那么收集的就是checked(勾选 or 未勾选,是布尔值)
    (2). v-model的初始值是数组,那么收集的的就是value组成的数组!!!

    备注:v-model的三个修饰符:

​ lazy:失去焦点再收集数据
​ number:输入字符串转为有效的数字
​ trim:输入首尾空格过滤

<body>
     <!-- 
			收集表单数据:
					若:<input type="text"/>,则v-model收集的是value值,用户输入的就是value值。
					若:<input type="radio"/>,则v-model收集的是value值,且要给标签配置value值。
					若:<input type="checkbox"/>
							1.没有配置input的value属性,那么收集的就是checked(勾选 or 未勾选,是布尔值)
							2.配置input的value属性:
									(1)v-model的初始值是非数组,那么收集的就是checked(勾选 or 未勾选,是布尔值)
									(2)v-model的初始值是数组,那么收集的的就是value组成的数组
					备注:v-model的三个修饰符:
									lazy:失去焦点再收集数据
									number:输入字符串转为有效的数字
									trim:输入首尾空格过滤
		-->
    <!-- 准备好一个容器 -->
    <div id="root">
        <form action="" @submit="demo">
            账号:<input type="text" v-model.trim="account"><br> <br>
            密码:<input type="password" v-model="password"><br> <br>
            年龄:<input type="number" v-model.number="age"><br> <br>
            性别:
            男<input type="radio" name="sex" value="男" v-model="sex">
            女<input type="radio" name="sex" value="女" v-model="sex"><br> <br>
            爱好:
            学习<input type="checkbox" value="学习" v-model="hobby">
            打游戏<input type="checkbox" value="打游戏" v-model="hobby">
            吃饭<input type="checkbox" value="吃饭" v-model="hobby"><br> <br>
            所属校区
            <select v-model="city">
                <option value="">请选择</option>
                <option value="北京">北京</option>
                <option value="西安">西安</option>
                <option value="武汉">武汉</option>
                <option value="上海">上海</option>
            </select><br> <br>
            <textarea v-model.lazy="other" name="" id="" cols="30" rows="10"></textarea><br> <br>
            <input type="checkbox" v-model="agree" name="" id="">阅读并接受<a href="#">用户协议</a>
            <button>提交</button>
        </form>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: {//data中用于存储数据,数据供el所指定的容器去使用,值
                account:'',
                password:'',
                sex:'男',
                hobby: [],
                city: '北京',
                other: '',
                agree: '',
                age: '',
            },
            methods: {
                demo(){
                    console.log(JSON.stringify(this._data))
                }
            },
        })
    </script>
</body>

过滤器

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

  1. 注册过滤器:Vue.filter(name,callback) 或 new Vue{filters:

  2. 使用过滤器:{{ xxx | 过滤器名}} 或 v-bind:属性 = “xxx | 过滤器名”
    备注:

    过滤器也可以接收额外参数、多个过滤器也可以串联

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

<body>
    <!-- 准备好一个容器 -->
    <div id="root">
        <button @click="time1">显示当前时间的时间戳</button>
        <h2>格式化前的时间</h2>
        <h4>{{timeNow}}</h4>
        <button @click="time2">显示当前时间</button>
        <h2>格式化后的时间</h2>
        <h4>{{fmtTime}}</h4>

        ----------------------------------------------------------------
        <!-- 简化 -->
        <h1>{{Date.now()}}</h1>
        <h1>{{time2(Date.now())}}</h1>
        <!-- 过滤器实现 -->
        <h4>{{Date.now() | timeFormater}}</h4>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false//设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: {//data中用于存储数据,数据供el所指定的容器去使用,值
                timeNow: '',
                fmtTime: ''
            },
            methods: {
                time1(){
                    this.timeNow = Date.now()
                },
                time2(){
                    this.fmtTime = dayjs(Date.now()).format('YYYY年MM月DD日 HH:mm:ss')
                    return this.fmtTime
                }
            },
            filters: {
                timeFormater(value){
                    return dayjs(Date.now()).format('YYYY年MM月DD日 HH:mm:ss')
                }
            }
            // computed: {
            //     fmtTime(){
            //         return dayjs(this.timeNow).format('YYYY年MM月DD日 HH:mm:ss')
            //     }
            // }
        })
    </script>
</body>

内置指令

v-text : 更新元素的 textContent

  • 作用:向其所在的节点中渲染文本内容。
  • 与插值语法的区别:v-text会替换掉节点中的内容,{{xx}}则不会。

v-html: 更新元素的 innerHTML

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

  • 与插值语法的区别:

    (1). v-html会替换掉节点中所有的内容,{{xx}}则不会。

    (2). v-html可以识别html结构。

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

    (1). 在网站上动态渲染任意HTML是非常危险的,容易导致XSS攻击。

    (2). 一定要在可信的内容上使用v-html,永不要用在用户提交的内容上!

v-pre指令

  • 跳过其所在节点的编译过程。
  • 可利用它跳过:没有使用指令语法、没有使用插值语法的节点,会加快编译。

v-if : 如果为true, 当前标签才会输出到页面

ref : 为某个元素注册一个唯一标识, vue对象通过$refs属性访问这个元素对象

v-cloak : 使用它防止闪现表达式, 与css配合: [v-cloak] { display: none }

  • 本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-cloak属性。
  • 使用css配合v-cloak可以解决网速慢时页面展示出{{xxx}}的问题。

v-once指令

  • v-once所在节点在初次动态渲染后,就视为静态内容了。
  • 以后数据的改变不会引起v-once所在结构的更新,可以用于优化性能。

v-else: 如果为false, 当前标签才会输出到页面

v-show : 通过控制display样式来控制显示/隐藏

v-for : 遍历数组/对象

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

v-bind : 强制绑定解析表达式, 可以省略v-bind

v-model : 双向数据绑定

自定义指令

定义语法

局部

directives : {
	'my-directive' : {
		bind (el, binding) {
			el.innerHTML = binding.value.toupperCase()
		}
	}
}

全局

Vue.directive('my-directive', function(el, binding){
	el.innerHTML = binding.value.toupperCase()
})


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

  • bind:指令与元素成功绑定时调用。
  • inserted:指令所在元素被插入页面时调用。
  • update:指令所在模板结构被重新解析时调用。

备注

  1. 指令定义时不加v-,但使用时要加v-;
  2. 指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名。

使用指令

<body>
		<!-- 准备好一个容器-->
		<div id="root">
			<h2>{{name}}</h2>
			<h2>当前的n值是:<span v-text="n"></span> </h2>
			<!-- <h2>放大10倍后的n值是:<span v-big-number="n"></span> </h2> -->
			<h2>放大10倍后的n值是:<span v-big="n"></span> </h2>
			<button @click="n++">点我n+1</button>
			<hr/>
			<input type="text" v-fbind:value="n">
		</div>
	</body>
	
	<script type="text/javascript">
		Vue.config.productionTip = false

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

		new Vue({
			el:'#root',
			data:{
				name:'尚硅谷',
				n:1
			},
			directives:{
				//big函数何时会被调用?1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时。
				/* 'big-number'(element,binding){
					// console.log('big')
					element.innerText = binding.value * 10
				}, */
				big(element,binding){
					console.log('big',this) //注意此处的this是window
					// console.log('big')
					element.innerText = binding.value * 10
				},
				fbind:{
					//指令与元素成功绑定时(一上来)
					bind(element,binding){
						element.value = binding.value
					},
					//指令所在元素被插入页面时
					inserted(element,binding){
						element.focus()
					},
					//指令所在的模板被重新解析时
					update(element,binding){
						element.value = binding.value
					}
				}
			}
		})
	</script>

生命周期

Vue对象的生命周期

  1. 又名:生命周期回调函数、生命周期函数、生命周期钩子。
  2. 是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数。
  3. 生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。
  4. 生命周期函数中的this指向是vm 或 组件实例对象。

  1. 初始化显示
  • beforeCreate()
  • created()
  • beforeMount()
  • mounted()
  1. 更新状态
  • beforeUpdate()
  • updated()
  1. 销毁 vue 实例: vm.$destory()
  • beforeDestory()
  • destoryed()

img原理图

img

<!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 :style="{opacity}">Hello,{{name}}{{id}}</h1> -->
        <h2>当前a的值为:{{a}}</h2>
        <button @click="a++">点击加一</button>
        <button @click="bye">点击销毁vm</button>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false //设置为 false 以阻止 vue 在启动时生成生产提示。
        new Vue({
            el: '#root', //el用于指定当前Vue实例为哪个服务器服务,值通常为css选择器字符串。
            data: { //data中用于存储数据,数据供el所指定的容器去使用,值
                name: '郝佳瑶',
                id: '卧槽',
                opacity: 1,
                a: 1,
            },
            methods: {
                add() {//加一
                    this.a = a++
                },
                bye() {//销毁
                    console.log('bye')
                    this.$destroy();
                }
            },
            beforeCreate() {
                console.log('beforeCreate')
                //console.log('this')
                //debugger;
            },
            created() {
                console.log('created')
                //console.log('this')
                //debugger;
            },
            beforeMount() {
                console.log('beforeMount')
                //console.log('this')
                //debugger;
            },
            beforeUpdate() {
                console.log('beforeUpdate')
                //console.log('this')
                //debugger;
            },
            updated() {
                console.log('updated')
                //console.log('this')
                //debugger;
            },
            //vue完成模板的解析并把初始的真实Dom元素放入页面后(挂载完毕)调用mounted
            mounted() {
                setInterval(() => {
                    this.opacity -= 0.01
                    if (this.opacity <= 0) this.opacity = 1
                }, 16)
            },
        })
        //通过外部的定时器实现(不推荐)
        // setInterval(() => {
        //     vm.opacity -= 0.01
        //     if (vm.opacity <= 0) vm.opacity = 1
        // }, 16)
    </script>
</body>

</html>

常用的生命周期方法

  • mounted(): 发送ajax请求, 启动定时器、绑定自定义事件、订阅消息等异步任务【初始化操作】
  • beforeDestroy(): 做收尾工作, 如: 清除定时器、解绑自定义事件、取消订阅消息等【首尾工作】

关于销毁Vue实例

  1. 销毁后借助Vue开发者工具看不到任何信息
  2. 销毁后自定义事件会失效,但原生DOM事件依然有效
  3. 一般不会在beforeDestroy操作数据,因为即使操作数据,也不会再触发更新流程了。

Vue组件化编程

非单文件组件

使用组件的三大步骤

  1. 定义组件(创建组件)
  2. 注册组件
  3. 使用组件(写组件标签)

如何定义一个组件

使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但有以下区别

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

  2. data必须写成函数——避免组件被复用时,数据存在引用关系

    【备注】使用tempalte可以配置组件结构

如何注册组件

  1. 局部注册:new Vue的时候传入components选项
  2. 全局注册:Vue.component(‘组件名’, 组件)
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>基本使用</title>
  <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
  <!-- 准备好一个容器-->
  <div id="root">
    <hello></hello>
    <hr>
    <h1>{{msg}}</h1>
    <hr>
    <!-- 第三步:编写组件标签 -->
    <school></school>
    <hr>
    <!-- 第三步:编写组件标签 -->
    <student></student>
  </div>

  <div id="root2">
    <hello></hello>
  </div>
</body>

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

  //第一步:创建school组件
  const school = Vue.extend({
    template: `
				<div class="demo">
					<h2>学校名称:{{schoolName}}</h2>
					<h2>学校地址:{{address}}</h2>
					<button @click="showName">点我提示学校名</button>	
				</div>
			`,
    // el:'#root', //组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器。
    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: 'Tom'
      }
    }
  })

  //第二步:全局注册组件
  Vue.component('hello', hello)

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

  new Vue({
    el: '#root2',
  })
</script>

</html>

注意点

关于组件名

一个单词组成
第一种写法(首字母小写):school
第二种写法(首字母大写):School

多个单词组成
第一种写法(kebab-case命名):my-school
第二种写法(CamelCase命名):MySchool(需要Vue脚手架支持)

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

关于组件标签

第一种写法:<school></school>
第二种写法:<school/> (不使用脚手架会导致后续组件不能渲染)

简写方式

const school = Vue.extend(options)可以简写成const school = options

<body>
  <!-- 准备好一个容器-->
  <div id="root">
    <h1>{{msg}}</h1>
    <school></school>
  </div>
</body>

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

  //定义组件
  const s = Vue.extend({
    name: 'atguigu',
    template: `
				<div>
					<h2>学校名称:{{name}}</h2>	
					<h2>学校地址:{{address}}</h2>	
				</div>
			`,
    data() {
      return {
        name: '尚硅谷',
        address: '北京'
      }
    }
  })

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

</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
1.5 组件嵌套
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>组件的嵌套</title>
  <!-- 引入Vue -->
  <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
  <!-- 准备好一个容器-->
  <div id="root">

  </div>
</body>

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

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

  //定义school组件
  const school = Vue.extend({
    name: 'school',
    template: `
				<div>
					<h2>学校名称:{{name}}</h2>	
					<h2>学校地址:{{address}}</h2>	
					<student></student>
				</div>
			`,
    data() {
      return {
        name: '尚硅谷',
        address: '北京'
      }
    },
    //注册组件(局部)
    components: {
      student
    }
  })

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

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

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

VueComponent

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

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

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

  4. 关于this指向
    ① 组件配置中:data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【VueComponent实例对象】
    ② new Vue(options)配置中:data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【Vue实例对象】

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

Vue的实例对象,以后简称为vm

<body>
    <!-- 准备好一个容器-->
    <div id="root">
        <!-- 第三步:编写组件标签 -->
        <school></school>
        <hr>
        <hello></hello>
    </div>
    </div>
    <script type="text/javascript">
        Vue.config.productionTip = false //设置为 false 以阻止 vue 在启动时生成生产提示。
        const school = Vue.extend({
            template: `
				<div class="demo">
					<h2>学校名称:{{schoolName}}</h2>
					<h2>学校地址:{{address}}</h2>       
				</div>
			`, // el:'#root', //组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器。
            data() {
                return {
                    schoolName: '尚硅谷',
                    address: '北京昌平'
                }
            },
        })
        const hello = Vue.extend({
            template: `<h2>{{msg}}</h2>`,
            data(){
                return {
                    msg: '你好呀'
                }
            }
        })
       
        //创建vm
        new Vue({
            el: '#root',
            data: {
                msg: '你好啊!'
            },
            //第二步:注册组件(局部注册)
            components: {
                school,
                hello
            }
        })
        
    </script>
</body>

单文件组件 vue 文件的组成

组成

  1. 模板页面
  1. JS 模块对象
  1. 样式

基本使用

  1. 引入组件
  2. 映射成标签
  3. 使用组件标签

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>

main.js

import App from './App.vue'
new Vue({
    el:'#root',
    template:'<App></App>',
    components: {
        App
    }
})

关于标签名与标签属性名书写问题

  1. 写法一: 一模一样
  2. 写法二: 大写变小写, 并用-连接

Vue脚手架

ref属性

  1. 被用来给元素或子组件注册引用信息(id的替代者)
  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
  3. 使用方式:
    1. 打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    2. 获取:this.$refs.xxx
<template>
  <div>
    <h1 v-text="msg" ref="title"></h1>
    <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button>
    <School ref="sch" />
  </div>
</template>

<script>
//引入School组件
import School from "./components/School";

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

props配置项

  1. 功能:让组件接收外部传过来的数据
  2. 传递数据:<Demo name="xxx"/>
  3. 接收数据:
    1. 第一种方式(只接收):props:['name']
    2. 第二种方式(限制类型):props:{name:String}
    3. 第三种方式(限制类型、限制必要性、指定默认值):
props:{
	name:{
	type:String, //类型
	required:true, //必要性
	default:'老王' //默认值
	}
}

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

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

<script>
export default {
  name: "Student",
  data() {
    console.log(this);
    return {
      msg: "我是一个尚硅谷的学生",
      myAge: this.age,
    };
  },
  methods: {
    updateAge() {
      this.myAge++;
    },
  },
  //简单声明接收
  // props:['name','age','sex']

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

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

mixin(混入)

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

  2. 使用方式:

    第一步定义混合:

    {
        data(){....},
        methods:{....}
        ....
    }
    
    

    第二步使用混入:

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

mixin.js

export const hunhe = {
  methods: {
    showName() {
      alert(this.name);
    },
  },
  mounted() {
    console.log("你好啊!");
  },
};
export const hunhe2 = {
  data() {
    return {
      x: 100,
      y: 200,
    };
  },
};

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
import {hunhe,hunhe2} from './mixin'
//关闭Vue的生产提示
Vue.config.productionTip = false

Vue.mixin(hunhe)
Vue.mixin(hunhe2)


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

组件中

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

<script>
// import {hunhe,hunhe2} from '../mixin'

export default {
  name: "Student",
  data() {
    return {
      name: "张三",
      sex: "男",
    };
  },
  // mixins:[hunhe,hunhe2]
};
</script>

Vue插件

  1. 功能:用于增强Vue

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

  3. 定义插件:

    对象.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()

plugins.js

export default {
  install(Vue, x, y, z) {
    console.log(x, y, z);
    //全局过滤器
    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, binding) {
        element.value = binding.value;
      },
    });

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

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

main.js

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

//应用(使用)插件
Vue.use(plugins, 1, 2, 3);
//创建vm
new Vue({
  el: "#app",
  render: (h) => h(App),
});

组件中使用

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

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

scoped样式

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

TodoList案例

User Footer.vue

<template>
  <div class="todo-footer" v-show="completeAll">
        <label>
          <input type="checkbox" :checked="isAll" @change="checkAll"/>
        </label>
        <span>
          <span>已完成{{completeTodo}}</span> / 全部 {{completeAll}}
        </span>
        <button class="btn btn-danger" @click="clearAll">清除已完成任务</button>
      </div>
</template>

<script>
export default {
    name:'UserFooter',
    props:['todos','checkAllTodo','clearAllTodo'],
    computed: {
      completeTodo(){
        let numberSum = 0
        this.todos.forEach((todo) => {
          if(todo.complete) numberSum++
        })
        return numberSum
      },
      completeAll(){
        return this.todos.length
      },
      isAll(){
        return this.completeTodo === this.completeAll && this.completeAll > 0
      }
    },
    methods: {
      checkAll(e){
        this.checkAllTodo(e.target.checked)
      },
      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>

UserHeader.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 {
    props:['addTodo'],
    name:'UserHeader',
    data() {
      return {
        title: '',
      };
    },
    methods:{
      add(){
        if(!this.title.trim()) return alert('输入不能为空')
        var todoObj = {id:nanoid(),title:this.title,complete:true}
        this.addTodo(todoObj)
        this.title = ''
      }
    },
}
</script>

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

UserItem.vue

<template>
  <li>
    <label>
      <input
        type="checkbox"
        :checked="todo.complete"
        @change="handleCheck(todo.id)"
      />
      <span>{{ todo.title }}</span>
    </label>
    <button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
  </li>
</template>

<script>
export default {
  name: "UserItem",
  props: ["todo", "checkTodo",'deleteTodo'],
  methods: {
    handleCheck(id) {
      this.checkTodo(id);
    },
    handleDelete(id){
      if(confirm('确定删除吗?')){
        console.log(id)
        this.deleteTodo(id)
      }
    }
  },
};
</script>

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

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

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

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

li:before {
  content: initial;
}

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

li:hover {
  background-color: #ddd;
}

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

UserList.vue

<template>
  <div class="todo-main">
    <user-item v-for="todoObj in todos" :key="todoObj.id" :todo="todoObj" :checkTodo="checkTodo" :deleteTodo="deleteTodo"/>
  </div>
</template>

<script>
import UserItem from './UserItem.vue'
export default {
    name:'UserList',
    components: {
       UserItem
    },
    props:['todos','checkTodo','deleteTodo']
    
}
</script>

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

App.vue

<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <user-header :addTodo="addTodo"/>
      <user-List :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"/>
      <user-footer :todos="todos" :clearAllTodo="clearAllTodo" :checkAllTodo="checkAllTodo"/>
  </div>
  </div>
</template>

<script>
    import UserHeader from './components/UserHeader.vue'
    import UserFooter from './components/UserFooter.vue'
    import UserList from './components/UserList.vue'
    export default {
        name: 'APP',
        components: {
            UserHeader,
            UserFooter,
            UserList,
          
        },
        data() {
          return {
            todos: [
              { id:'001',title: '吃饭', complete: true },
              { id:'002',title: '睡觉', complete: false },
              { id:'003',title: '敲代码', complete: true }
            ],
          }
        },
        methods:{
          addTodo(todoObj){
            this.todos.unshift(todoObj)
          },
          checkTodo(id){
          this.todos.forEach((todo)=>{
            if(todo.id === id) todo.complete = !todo.complete
          });
          
          },
          deleteTodo(id){
            this.todos = this.todos.filter(todo => todo.id !== id)
          },
          checkAllTodo(complete){
            this.todos.forEach((todo) => {
              todo.complete = complete
            })
          },
          clearAllTodo(){
            this.todos = this.todos.filter((todo) => {
              return !todo.complete
            })
          }
        }

    }
</script>

<style>
.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>

image-20220505220524370

总结TodoList案例

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

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

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

​ 2). 一些组件在用:放在他们共同的父组件上(状态提升)。

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

  1. props适用于:
    (1).父组件 ==> 子组件 通信

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

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

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

LocalStorage

LocalStorage的优点:

  • 在大小方面,LocalStorage的大小一般为5MB,可以储存更多的信息

  • LocalStorage是持久储存,并不会随着页面的关闭而消失,除非主动清理,不然会永久存在

  • 仅储存在本地,不像Cookie那样每次HTTP请求都会被携带

LocalStorage的缺点:

  • 存在浏览器兼容问题,IE8以下版本的浏览器不支持
  • 如果浏览器设置为隐私模式,那我们将无法读取到LocalStorage
  • LocalStorage受到同源策略的限制,即端口、协议、主机地址有任何一个不相同,都不会访问

LocalStorage的使用场景:

  • 有些网站有换肤的功能,这时候就可以将换肤的信息存储在本地的LocalStorage中,当需要换肤的时候,直接操作LocalStorage即可
  • 在网站中的用户浏览信息也会存储在LocalStorage中,还有网站的一些不常变动的个人信息等也可以存储在本地的LocalStorage中
<body>
    <h2>localStorage</h2>
    <button onclick="saveData()">保存数据</button>
    <button onclick="readData()">读取数据</button>
    <button onclick="deleteData()">删除数据</button>
    <button onclick="deleteAllData()">清空数据</button>
    <script>
        let p = {name:"郝佳瑶",age:'18'}
        function saveData(){
            localStorage.setItem('msg','hello')
            localStorage.setItem('msg2','519')
            localStorage.setItem('person',JSON.stringify(p))
        }
        
        function readData(){
            console.log(localStorage.getItem('msg'))
            console.log(localStorage.getItem('msg2'))
            console.log(JSON.parse(localStorage.getItem('person')))
        }

        function deleteData(){
            localStorage.removeItem('person')
        }
        
        function deleteAllData(){
            localStorage.clear()
        }
    </script>
</body>

SessionStorage

SessionStorage与LocalStorage对比:

  • SessionStorage和LocalStorage都在本地进行数据存储;
  • SessionStorage也有同源策略的限制,但是SessionStorage有一条更加严格的限制,SessionStorage只有在同一浏览器的同一窗口下才能够共享;
  • LocalStorage和SessionStorage都不能被爬虫爬取;

SessionStorage的使用场景

  • 由于SessionStorage具有时效性,所以可以用来存储一些网站的游客登录的信息,还有临时的浏览记录的信息。当关闭网站之后,这些信息也就随之消除了。
<body>
    <h2>sessionStorage</h2>
    <button onclick="saveData()">保存数据</button>
    <button onclick="readData()">读取数据</button>
    <button onclick="deleteData()">删除数据</button>
    <button onclick="deleteAllData()">清空数据</button>
    <script>
        let p = {name:"郝佳瑶",age:'18'}
        function saveData(){
            sessionStorage.setItem('msg','hello')
            sessionStorage.setItem('msg2','519')
            sessionStorage.setItem('person',JSON.stringify(p))
        }
        
        function readData(){
            console.log(sessionStorage.getItem('msg'))
            console.log(sessionStorage.getItem('msg2'))
            console.log(JSON.parse(sessionStorage.getItem('person')))
        }

        function deleteData(){
            sessionStorage.removeItem('person')
        }
        
        function deleteAllData(){
            sessionStorage.clear()
        }
    </script>
</body>

组件的自定义事件

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

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

  3. 绑定自定义事件:

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

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

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

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

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

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

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

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

全局事件总线

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

  2. 安装全局事件总线:

    main.js

    import Vue from 'vue'
    import App from './App.vue'
    
    Vue.config.productionTip = false
    new Vue({
      render: h => h(App),
      beforeCreate(){
        Vue.prototype.$bus = this //安装全局总线
      }
    }).$mount('#app')
    
  3. 使用事件总线:

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

​ School.vue

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

<script>
export default {
    name:'mySchool',
    data() {
        return {
            name: '绿野',
            address: '陕西'
        };
    },
    mounted() {
        this.$bus.$on('hello',(data) => {
            console.log('school组件,收到数据',data)
        })
    },
    beforeDestroy() {
        this.$bus.$off('hello')
    },
}
</script>

<style>
   .school {
       background-color: skyblue;
       padding: 5px;
   }
</style>

​ 提供数据:this.$bus.$emit('xxxx',数据)

​ Student.vue

<template>
  <div class="student">
      <h2>学生姓名:{{name}}</h2>
      <h2>学生性别:{{sex}}</h2>
      <button @click="sendStudentName">点击</button>
  </div>
</template>

<script>
export default {
    name:'myStudent',
    data() {
        return {
            name: '郝佳瑶',
            sex:'男'
        };
    },
    methods: {
        sendStudentName(){
            this.$bus.$emit('hello',this.name)
        }
    },
}
</script>
    
<style>
    .student{
            background-color: pink;
            padding: 5px;
            margin-top: 30px;
        }
</style>
  1. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。

消息订阅与发布(PubSubJS 库)

订阅消息

PubSub.subscribe('msg', function(msg, data){})

发布消息

PubSub.publish('msg', data)

示例

订阅消息(绑定事件监听)

import PubSub from 'pubsub-js'

export default {
	mounted () {
		// 订阅消息(deleteTodo)
		PubSub.subscribe('deleteTodo', (msg, index) => {
		this.deleteTodo(index)
		})
	}
}

发布消息(触发事件)

// this.deleteTodo(this.index)
// 发布消息(deleteTodo)
PubSub.publish('deleteTodo', this.index)

注意

优点: 此方式可实现任意关系组件间通信(数据)

事件的2 个重要操作

  1. 绑定事件监听(订阅消息)
    目标: 标签元素<button>
    事件名(类型): click/focus
    回调函数: function(event){}
  2. 触发事件(发布消息)
    DOM 事件: 用户在浏览器上对应的界面上做对应的操作
    自定义: 编码手动触发

总结

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

  2. 使用步骤:

    1. 安装pubsub:npm i pubsub-js
    2. 引入: import pubsub from 'pubsub-js'
    3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
  3. 提供数据:pubsub.publish('xxx',数据)

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

动画与过渡

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

  2. 写法:

​ 准备好样式:

​ 元素进入的样式:
​ v-enter:进入的起点
​ v-enter-active:进入过程中
​ v-enter-to:进入的终点
​ 元素离开的样式:
​ v-leave:离开的起点
​ v-leave-active:离开过程中
​ v-leave-to:离开的终点
​ 使用包裹要过度的元素,并配置name属性:

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

axios

使用Vue-cli配置代理

App.vue

<template>
  <div id="app">
    <button @click="getmsg">获取信息</button>
  </div>
</template>

<script>
import axios from 'axios'


export default {
  name: 'App',
  methods: {
    getmsg(){
      axios.get('http://localhost:8081/axios/user/all').then(
        respones => {
          console.log('请求成功了',respones.data)
        },
        error => {
          console.log('请求失败了',error.message)
        }
      )
    }
  },
}
</script>

方法一

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

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

方法二

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

module.exports = {
	devServer: {
      proxy: {
      '/api1': {// 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api1': ''}
      },
      '/api2': {// 匹配所有以 '/api2'开头的请求路径
        target: 'http://localhost:5001',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {'^/api2': ''}
      }
    }
  }
}
/*
   changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
   changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
   changeOrigin默认值为true
*/
  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。

案例

myList.vue

<template>
  <div class="row">
      <!-- 展示用户列表 -->
    <div v-show="info.users.length" class="card" v-for="user in info.users" :key="user.login">
      <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:'myList',
    data() {
        return {
            info:{
            isFirst:true,
            isLoading:false,
            errMsg:'',
            users: []
            }
        };
    },
    mounted() {
        this.$bus.$on('updataListData',(dataObj) => {
            this.info = {...this.info,...dataObj}//ES6语法
        })
    },
}
</script>

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

mySearch.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"
      />
      <button @click="SearchUser">Search</button>
    </div>
  </section>
</template>

<script>
import axios from "axios";
export default {
  name: "mySearch",
  data() {
    return {
      keyword: "",
    };
  },
  methods: {
    SearchUser() {
        //请求前更新List数据
      this.$bus.$emit('updataListData',{isFirst:false,isLoading:true,errMsg:'',users:[]})
      axios.get(`http://api.github.com/search/users?q=${this.keyword}`).then(
        respones => {
          console.log('请求成功了')
          //请求成功后
          this.$bus.$emit('updataListData',{isLoading:false,errMsg:'',users:respones.data.items})
        },
        error => {
          console.log('请求失败了',error.message)
          //请求失败后
          this.$bus.$emit('updataListData',{isLoading:false,errMsg:error.message,users:[]})
        }
      );
    },
  },
};
</script>

<style>
</style>

App.vue

<template>
  <div class="container">
    <my-search/>
    <my-list/>
  </div>
</template>

<script>

import mySearch from "./components/mySearch.vue";
import myList from "./components/myList.vue";

export default {
  components: { mySearch , myList}, //不能用main作为标签名,就换一个名字
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

页面展示

image-20220513212516214插槽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>

作用域插槽

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

父组件中:

<Category>
	<template scope="scopeData">
		<!-- 生成的是ul列表 -->
		<ul>
			<li v-for="g in scopeData.games" :key="g">{{g}}</li>
		</ul>
	</template>
</Category>

<Category>
	<template slot-scope="scopeData">
		<!-- 生成的是h4标题 -->
		<h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
	</template>
</Category>

子组件中:

<template>
    <div>
        <slot :games="games"></slot>
    </div>
</template>

<script>
    export default {
        name:'Category',
        props:['title'],
        //数据在子组件自身
        data() {
            return {
                games:['红色警戒','穿越火线','劲舞团','超级玛丽']
            }
        },
    }
</script>

Vuex

原理

image-20220524154413517 state

  1. vuex 管理的状态对象
  2. 它应该是唯一的

mutations

  1. 包含多个直接更新state 的方法(回调函数)的对象
  2. 谁来触发: action 中的commit(‘mutation 名称’)
  3. 只能包含同步的代码, 不能写异步代码

actions

  1. 包含多个事件回调函数的对象
  2. 通过执行: commit()来触发mutation 的调用, 间接更新state
  3. 谁来触发: 组件中: $store.dispatch(‘action 名称’, data1) // ‘zzz’
  4. 可以包含异步代码(定时器, ajax)

getters

  1. 包含多个计算属性(get)的对象
  2. 谁来读取: 组件中: $store.getters.xxx

mapState,mapGetters

​ 让代码简洁

<template>
  <div>
    <h1>当前的求和为:{{ sum }}</h1>
    <h1>和放大10倍:{{ bigSum }}</h1>
    <h1>我的名字是{{ name }},今年{{ age }}了</h1>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(n)">+</button>
    <button @click="decrement(n)">-</button>
    <button @click="incrementOdd(n)">当前求和为奇数再加</button>
    <button @click="incrementWait(n)">等一等再加</button>
  </div>
</template>
  1. 引入mapState,mapGetters:

    import { mapState,mapGetters } from "vuex";
    
  2. 计算属性:

      computed: {
        //借助mapState生成计算属性,从state中读取数据(对象写法)
        // ...mapState({ sum: "sum", myName: "name", myAge: "age" }),
        //数组写法
        ...mapState(['sum','name','age']),
        // bigSum() {
        //   return this.$store.getters.bigSum;
        // },
        //借助mapGetters生成计算属性,从getters中读取数据(对象写法)
        ...mapGetters({ bigSum: "bigSum"}),
        //数组写法
        ...mapGetters(['bigSum'])
      },
    

mapMutations, mapActions

引入

import { mapState,mapGetters,mapMutations, mapActions } from "vuex";

让代码简洁

体现在方法中

 methods: {
    // increment() {
    //   this.$store.commit("JIA", this.n);
    // },
    // decrement() {
    //   this.$store.commit("JIAN", this.n);
    // },

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

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

        //借助mapActions生成对应的方法,方法中会调用dispatch去联系actions
    ...mapActions({incrementOdd:"jiaOdd",incrementWait:"jiaWait"})
  },

模块化+命名空间

  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
     }
   })
  1. 开启命名空间后,组件中读取state数据:
   //方式一:自己直接读取
   this.$store.state.personAbout.list
   //方式二:借助mapState读取:
   ...mapState('countAbout',['sum','school','subject']),
  1. 开启命名空间后,组件中读取getters数据:
   //方式一:自己直接读取
   this.$store.getters['personAbout/firstPersonName']
   //方式二:借助mapGetters读取:
   ...mapGetters('countAbout',['bigSum'])
  1. 开启命名空间后,组件中调用dispatch
   //方式一:自己直接dispatch
   this.$store.dispatch('personAbout/addPersonWang',person)
   //方式二:借助mapActions:
   ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
  1. 开启命名空间后,组件中调用commit
   //方式一:自己直接commit
   this.$store.commit('personAbout/ADD_PERSON',person)
   //方式二:借助mapMutations:
   ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),

demo1: 计数器

在src目录下创建store/index.js

image-20220524154717638

npm i vuex@3下载Vuex插件

实现页面展示

image-20220526112933537

main.js

import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
  render: h => h(App),
  store,
}).$mount('#app')

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import { nanoid } from 'nanoid'
import axios from 'axios'
Vue.use(Vuex)
//该文件用于创建Vuex中最核心的store

//准备action  用于相应组件中的动作
const actions = {
    // jia(context,value){
    //     context.commit('JIA',value)
    // },
    // jian(context,value){
    //     context.commit('JIAN',value)
    // },
    jiaOdd(context,value){
        if(context.state.sum % 2){
            context.commit('JIA',value)
        }
    },
    jiaWait(context,value){
        setTimeout(() => {
            context.commit('JIA',value)
        }, 1000);
    },
    addObj(context){
        axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
            respose => {
                context.commit('ADD_PERSON',respose.data)
            },
            error => {
                console.log(error.message)
            }
        )
    }
}
//准备mutations  用于操作数据
const mutations = {
    JIA(state,value){
        state.sum += value
    },
    JIAN(state,value){
        state.sum -= value
    },
    ADD_PERSON(state,value){
        if(value != '' & isNaN(value)){
            const personObj = {id:nanoid(),name:value}
            state.personList.unshift(personObj)
        }
    }
}
//准备state  用于存储数据
const state = {
    sum: 0,
    name:'郝佳瑶',
    age:22,
    personList:[
        {id:17,name:'李四'}
    ]
}
//准备state  用于数据加工
const getters = {
    bigSum(state){
        return state.sum*10
    }
}

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

count.vue

<template>
  <div>
    <h1>当前的求和为:{{ sum }}</h1>
    <h1>和放大10倍:{{ bigSum }}</h1>
    <h1>我的名字是{{ name }},今年{{ age }}了</h1>
    <h1>Person组件的总人数是:{{personList.length}}</h1>
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(n)">+</button>
    <button @click="decrement(n)">-</button>
    <button @click="incrementOdd(n)">当前求和为奇数再加</button>
    <button @click="incrementWait(n)">等一等再加</button>
  </div>
</template>

<script>
import { mapState,mapGetters,mapMutations, mapActions } from "vuex";
export default {
  name: "myCount",
  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"}),

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

        //借助mapActions生成对应的方法,方法中会调用dispatch去联系actions
    ...mapActions({incrementOdd:"jiaOdd",incrementWait:"jiaWait"})
  },

  computed: {
    //借助mapState生成计算属性,从state中读取数据(对象写法)
    // ...mapState({ sum: "sum", myName: "name", myAge: "age" }),
    //数组写法
    ...mapState(['sum','name','age','personList']),
    // bigSum() {
    //   return this.$store.getters.bigSum;
    // },
    //借助mapGetters生成计算属性,从getters中读取数据(对象写法)
    //...mapGetters({ bigSum: "bigSum"}),
    //数组写法
    ...mapGetters(['bigSum'])
  },
};
</script>

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

person.vue

<template>
  <div>
    <h1>Count组件的sum是:{{sum}}</h1>
    <input type="text" v-model="name" />
    <button @click="add(name)">添加</button>
    <button @click="addObj">随即添加</button>
    <ul>
        <li v-for="p in personList" :key="p.id">{{p.name}}</li>
    </ul>
  </div>
</template>

<script>
import { mapState,mapMutations,mapActions } from 'vuex';

export default {
  name: "myPersons",
  data() {
    return {
      name: "",
    };
  },
  computed:{
    ...mapState(['personList','sum'])
  },
  methods: {
    ...mapMutations({add:"ADD_PERSON"}),
    ...mapActions(['addObj'])
  },
};
</script>

<style>
</style>

Vue-router

下载路由

npm i vue-router@3

npm i vue-router

基本路由

基本效果

image-20220526164229568

image-20220526164257946

注册路由器

main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import router from './router'
Vue.config.productionTip = false
Vue.use(VueRouter)

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

路由器模块: src/router/index.js

//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import myAbout from '../pages/About.vue'
import myHome from '../pages/Home.vue'
//创建并暴露一个路由器
export default new VueRouter({
    routes: [
        { path: '/about', component: myAbout },
        { path: '/home', component: myHome },
    ]
})

应用组件: App.vue

<template>
  <div id="app">
    <div class="row">
      <my-banner/>
    </div>
    <div class="row">
      <div class="col-xs-2 col-xs-offset-2">
        <div class="list-group">
          <!-- 原始html中我们使用a标签来实现跳转 -->
          <!-- <a class="list-group-item" active href="./about.html">About</a>
          <a class="list-group-item" href="./homr.html">About</a> -->
          <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 myBanner from './components/Banner.vue'
export default {

  name: 'App',
  components: {
    myBanner,
}
}
</script>

路由组件

存放在pages里面

image-20220526164357377

About.vue

<template>
  <div>
      <h2>我是About的内容</h2>
  </div>
</template>

<script>
export default {
    name:'myAbout'
}
</script>

Home.vue

<template>
  <div>
      <h2>我是Home的内容</h2>
  </div>
</template>

<script>
export default {
    name:'myHome'
}
</script>

普通组件

Banner.vue

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

<script>
export default {
    name:'myBanner'
}
</script>

嵌套路由

显示效果

image-20220526171038161

image-20220526171056766

结构

image-20220526171404040

路由组件

Home.vue修改

<template>
  <div>
    <h2>Home</h2>
    <div>
      <ul class="nav nav-tabs">
        <li>
          <router-link to="/home/news">News</router-link>
          <router-link to="/home/message">Message</router-link>
        </li>
      </ul>

      <div>
        <router-view></router-view>
        <hr />
      </div>
    </div>
  </div>
</template>

<script>
export default {
    name:'myHome'
}
</script>

新增组件New.vue Message.vue

Message.vue

<template>
  <div>
      <ul>
    <li v-for="message in messages" :key="message.id">
      <a href="#">{{ message.title }}</a>
    </li>
  </ul>
  </div>
</template>

<script>
export default {
  name: "myMessage",
  data() {
    return {
      messages: [],
    };
  },
  mounted() {
    //模拟ajax请求从后台获取数据
    setTimeout(() => {
      const messages = [
        {
          id: 1,
          title: "message001",
        },
        {
          id: 2,
          title: "message002",
        },
        {
          id: 3,
          title: "message003",
        },
      ];
      this.messages = messages;
    }, 1000);
  },
};
</script>

New.vue

<template>
<div>
  <ul>
    <li v-for="(news, index) in newsArr" :key="index">{{ news }}</li>
  </ul>
</div>
</template>

<script>
export default {
    name: "myNews",
  data() {
    return {
      newsArr: ["news001", "news002", "news003", "news004"],
    };
  },
};
</script>

index.js修改

index.js

//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import myAbout from '../pages/About.vue'
import myHome from '../pages/Home.vue'
import myNews from '../pages/News.vue'
import myMessage from '../pages/Message.vue'
//创建并暴露一个路由器
export default new VueRouter({
    routes: [{
            path: '/about',
            component: myAbout
        },
        {
            path: '/home',
            component: myHome,
            children: [{
                    path: 'news',
                    component: myNews
                },
                {
                    path: 'message',
                    component: myMessage
                },
            ]
        },
    ]
})

路由的query参数

传递参数

<!-- 跳转并携带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>

接收参数:

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

命名路由

  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>
    

路由的params参数

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

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

传递参数

<!-- 跳转并携带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配置!

接收参数:

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

路由的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,
		  a: 1,
		  b: 'hello'
		}
	}
}

跳转去组件的具体代码

<template>
  <ul>
      <h1>Detail</h1>
      <li>消息编号:{{id}}</li>
      <li>消息标题:{{title}}</li>
      <li>a:{{a}}</li>
      <li>b:{{b}}</li>
  </ul>
</template>

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

<router-link>的replace属性

  1. 作用:控制路由跳转时操作浏览器历史记录的模式
  2. 浏览器的历史记录有两种写入方式:分别为push和replace,push是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
  3. 如何开启replace模式:<router-link replace .......>News

编程式路由导航

  1. 作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活
  2. 具体编码:
//$router的两个API
this.$router.push({
	name:'xiangqing',
		params:{
			id:xxx,
			title:xxx
		}
})

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

缓存路由组件

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

  2. 具体编码:

    这个 include 指的是组件名

    <keep-alive include="News"> 
        <router-view></router-view>
    </keep-alive>
    

两个新的生命周期钩子

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

  • activated路由组件被激活时触发。
  • deactivated路由组件失活时触发。

这两个生命周期钩子需要配合前面的缓存路由组件使用(没有缓存路由组件不起效果)

<template>
  <div>
    <ul>
      <li :style="{ opacity }">郝佳瑶</li>
      <li v-for="(news, index) in newsArr" :key="index">{{ news }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "myNews",
  data() {
    return {
      newsArr: ["news001", "news002", "news003", "news004"],
      opacity: 1,
    };
  },
  activated() {
    console.log("News组件被激活了");
    this.timer = setInterval(() => {
      console.log("@");
      this.opacity -= 0.01;
      if (this.opacity <= 0) this.opacity = 1;
    }, 16);
  },
  deactivated() {
    console.log("News组件失活了");
    clearInterval(this.timer);
  },
};
</script>

路由守卫

  1. 作用:对路由进行权限控制
  2. 分类:全局守卫、独享守卫、组件内守卫

全局守卫

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

//全局后置守卫:初始化时执行、每次路由切换后执行
router.afterEach((to,from)=>{
	console.log('afterEach',to,from)
	if(to.meta.title){ 
		document.title = to.meta.title //修改网页的title
	}else{
		document.title = 'vue_test'
	}
})

完整代码

// 这个文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
// 引入组件
import About from '../pages/About.vue'
import Home from '../pages/Home.vue'
import Message from '../pages/Message.vue'
import News from '../pages/News.vue'
import Detail from '../pages/Detail.vue'
// 创建并暴露一个路由器
const router = new VueRouter({
    routes: [
        {
            path: '/home',
            component: Home,
            meta:{title:'主页'},
            children: [
                {
                    path: 'news',
                    component: News,
                    meta:{isAuth:true,title:'新闻'}
                },
                {
                    path: 'message',
                    name: 'mess',
                    component: Message,
                    meta:{isAuth:true,title:'消息'},
                    children: [
                        {
                            path: 'detail/:id/:title',
                            name: 'xiangqing',
                            component: Detail,
                            meta:{isAuth:true,title:'详情'},
                            props($route) {
                                return {
                                    id: $route.query.id,
                                    title:$route.query.title,
									a: 1,
									b: 'hello'
                                }
                            }
                        }
                    ]
                }
            ]
        },
        {
            path: '/about',
            component: About,
            meta:{ title: '关于' }
        }
    ]
})

// 全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
    console.log('前置路由守卫', to, from);
    if(to.meta.isAuth) {
        if(localStorage.getItem('school') === 'zhejiang') {
            // 放行
            next()
        } else {
            alert('学校名不对,无权查看')
        }
    } else {
        next()
    }
})

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

export default router

独享守卫

就是在 routes 子路由内写守卫

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

组件内守卫

在具体组件内写守卫

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

路由器的两种工作模式

  1. 对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值。
  2. hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。
  3. hash模式:

​ 地址中永远带着#号,不美观 。
​ 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
兼容性较好。

  1. history模式:

​ 地址干净,美观 。
​ 兼容性和hash模式相比略差。
​ 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。

posted @ 2022-05-19 17:43  每一个困难都能克服我  阅读(58)  评论(0)    收藏  举报