前端学习日志(Vue)

本文深入介绍了Vue.js的核心概念,包括模板语法、指令、数据绑定、计算属性、事件处理、组件化、路由和状态管理。通过实例演示了如何创建Vue实例、使用计算属性和监听器、实现组件通信、运用Vuex进行状态管理和Vue Router进行路由配置。此外,还涵盖了Vue的生命周期、插槽、渲染函数以及自定义指令等高级特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


2.3
Vue为渐进式
一个vue实例对应一个容器

 <div id="id">
        <h1>hello, {{name}}</h1>
 </div>
 <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        const x = new Vue({
            el:'#id',//指定为那个服务器进行服务,值通常为css选择器字符串
            data :{
                name: 'jth'
            }
        }
        )
 </script>

1.想让vue工作,就必须创建一个vue实例,且要传入一个配置对象
2.root容器中的代码依然符合html规范,只不过混入了一些特殊的Vue语法
3.root容器里的代码被称为Vue模板
4.Vue实例和容器是一一对应的
5.真实开发中只有一个Vue实例,并且会配合组件一起使用
6.{{xxx}}中的xxx要写js表达式,且xxx可以自动读取data中的所有属性。
7.一旦data中的数据发生改变,那么页面中用到该数据的地方会自动更新

模板语法

插值语法

如上面的所示
解析标签体内容

指令语法

  <div id="id">
        <h1>hello, {{name}}</h1>
        <a v-bind:href="url.toUpperCase()" target="_blank">点我1</a>
        <a :href="url" target="_blank" rel="noopener noreferrer">点我2</a>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        const x = new Vue({
            el:'#id',//指定为那个服务器进行服务,值通常为css选择器字符串
            data :{
                name: 'jth',
                url:'http://www.baidu.com'
            }
        }
        );
    </script>

解析标签(属性,绑定事件,标签体内容)

数据绑定

<div id="id">
        <span>单行数据绑定</span>
        <input type="text" :value="name">
        <span>双向数据绑定</span>
        <input type="text" v-model:value="name">//v-model只能用于表单类元素(v-model="name")
</div>
 data:function(){
                return{
                    name: 'jth',
                url:'http://www.baidu.com'
                }
}//学习挂件时要用函数式,此处的this是Vue实例对象

MVVM模型

1.M,模型(model)data中的数据
2.V,视图(view):模板代码
3.VM,视图模型(view model)Vue实例
Object.definePropty

let person = {
            name:"jth",
            sex:"male",

        }
        Object.defineProperty(person,'age',{
            value:18
        })
        console.log(Object.keys(person));

无法打印出新加的属性
2.7

数据代理

通过一个对象代理另一个对象的操作(读/写)

 let obj1 = {x:200}
 let obj2 = {y:300}
        
 Object.defineProperty(obj1,'x',{
 get(){
     return obj1.x;
 },
 set(value){
    obj1.x = value
}
})

vm通过数据代理将_data中的name and address通过set and get 提取处理,简化了以后的操作
_data中将data做了一点小小的改动,其中含有数据劫持,加了监听器,可以检测到_data中的数据的改变,并实时的改变页面上的显示

事件处理

1.事件的基本使用

    <div id="id">
        <div>欢迎来到{{name}}</div>
        <button v-on:click = "showInfo">click me</button>
        <button @click = "showInfo1(676,$event)">click me</button>

    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                name:"jth",
                address:"chengdu"
            },
            methods:{  //不做数据代理
                showInfo(event){
                    alert("son of bitch");
                    console.log(event.target.innerText);
                    console.log(this);//this 是 vm;
                },
                showInfo1(num,event){
                    console.log(num,event)
                }
            }
        })
    </script>

methods不能用箭头函数,否则this就不会指向vm,而是指向window
其中所配置的函数 this的指向是vm,或者组件实例对象
@click=“demo: = @click = “demo(”$event”)",效果一致,后者可以传参
2.事件修饰符

    <div id="id">
        <div>欢迎来到{{name}}</div>
        <a href="http://www.bilibili.com" @click.prevent = "showInfo">click me to get information</a>
        1.prevent 阻止默认事件
        2.stop    阻止冒泡
        3.once    事件只触发一次
        4.capture 使用事件的捕获模式
        5.self    只有event.target是当前操作的元素时才触发事件
        6.passive 事件的默认行为立即执行,无需等待
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                name:"jth"
            },
            methods:{
                showInfo(e){
                    e.preventDefault();
                    console.log("information")
                }
            }
        })
    </script>

修饰符可以连续写
键盘事件
在这里插入图片描述
tab(用keydown)不然会改变焦点

计算属性

插值语法

    <div id="id"><input type="text" v-model = "firstname"><br><input type="text" v-model = "lastname"><br>
        名字<div>{{firstname}} - {{lastname}}</div>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                firstname:"张",
                lastname:"三"
            }
        })
    </script>

methods语法

    <div id="id"><input type="text" v-model = "firstname"><br><input type="text" v-model = "lastname"><br>
        名字<div>{{fullname()}}</div>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                firstname:"张",
                lastname:"三"
            },
            methods:{
                fullname(){
                    return this.firstname + "-" + this.lastname
                }
            }
        })
    </script>

计算属性

    <div id="id"><input type="text" v-model = "firstname"><br><input type="text" v-model = "lastname"><br>
        名字<div>{{fullname}}</div>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                firstname:"张",
                lastname:"三"
            },
            computed:{
                fullname:{//get调用时间1.初次调用fullname时2.所依赖的数据发生变化时,get会缓存
                    get(){
                        return this.firstname + "-" + this.lastname;//this指向vm
                    }
                }
            }
            
        })
    </script>

当get调用时会进行缓存
在这里插入图片描述
简写形式

 <div id="id"><input type="text" v-model = "firstname"><br><input type="text" v-model = "lastname"><br>
        名字<div>{{fullname}}</div>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                firstname:"张",
                lastname:"三"
            },
            //简写形式
            computed:{
                fullname(){
				 return this.firstname + "-" + this.lastname;

					}
                   
                
            }
            
        })
    </script>

只有当不会对fullname进行改变的时候可以对其进行简写形式

监视属性

    <div id="id">
        <h2>今天天气很{{info}}</h2>
        <button @click = "change">切换天气</button>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                isHot:true
            },
            computed:{
                info(){
                    return this.isHot ? "炎热" : "凉爽";
                }
            },
            methods: {
                change(){
                    this.isHot=!this.isHot;
                }  
            },
        })
    </script>

进行监听

    <div id="id">
        <h2>今天天气很{{info}}</h2>
        <button @click = "change">切换天气</button>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                isHot:true
            },
            computed:{
                info(){
                    return this.isHot ? "炎热" : "凉爽";
                }
            },
            methods: {
                change(){
                    this.isHot=!this.isHot;
                }  
            },
            watch:{
                info:{
                    //当isHot被修改时调用handler
                    immediate:true,
                    handler(newValue,oldValue){
                        console.log(newValue,oldValue)
                    }
                }
            }
            
        })
        vm.$watch("isHot",{
             immediate:true,
             handler(newValue,oldValue){
                console.log(newValue,oldValue)
          }
        })
    </script>

在这里插入图片描述
其属性既可以是data中的,也可以是计算属性

深度监视

    <div id="id">
        <h2>今天天气很{{info}}</h2>
        <button @click = "change">切换天气</button>
        <div>{{numbers.a}}</div>
        <button @click = "add">点我让a+1</button>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                isHot:true,
                numbers:{
                    a:1,
                    b:2
                }
            },
            computed:{
                info(){
                    return this.isHot ? "炎热" : "凉爽";
                }
            },
            methods: {
                change(){
                    this.isHot=!this.isHot;
                },
                add(){
                    this.numbers.a++;
                }  
            },
            watch:{
                info:{
                    //当isHot被修改时调用handler
                    immediate:true,
                    handler(newValue,oldValue){
                        console.log(newValue,oldValue)
                    }
                },
                // 'numbers.a':{
                //     handler(){
                //         console.log("a被改变了")
                //     }
                // }
                // 深度监视
                numbers:{
                    deep:true,
                    handler(){
                        console.log("numbers被改变了")
                    }
                }

            }
            
        })
        vm.$watch("ishot",{

        })
    </script>

在这里插入图片描述
在这里插入图片描述

对象写法,适用于,要绑定的样式个数确定,名字也确定,但是要动态的确定用不用

 data:{
                Ob:{
                    a:true,
                    b:false,
                    c:false
                }
            },

绑定class样式写法-字符串写法,适用于:要绑定的样式的类名不确定,需动态指定

 <div id="id">
        <div class="basic" :class = "backgroundcolor"></div>
        <button @click="changeColor">点我切换颜色</button>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                arrCl:['a','b','c'],
                backgroundcolor: 'a'
            },
            methods: {
                changeColor(){
                    let arr = this.arrCl
                    let index = Math.floor(Math.random()*3)
                    this.backgroundcolor = arr[index]
                }
            },
        })

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

 <div class="basic" :class = "arrCl"></div>

在这里插入图片描述

条件渲染

在这里插入图片描述
v-if将直接被移除,若将来产生交互,要获取该结点 ,则会报错,无法获取该节点

            <div v-if = "n == 1 "></div>
            <div v-show = "true"></div>

列表渲染

1.基本列表

在这里插入图片描述

  <!-- 遍历数组 -->
            <h2>人员列表</h2>
            <li v-for = "(p,index) in persons" :key="p.id">
                {{p.name}} - {{p.age}}
            </li>
            <br>
            <!-- 遍历对象 -->
            <h2>车辆信息</h2>
            <li v-for = "(value,key) in cars" :key = 'key'>
                {{key}}-{{value}}
            </li>
            <br>
            <!-- 遍历字符串 -->
            <h2>遍历字符串</h2>
            <li v-for="(char,index) in str":key="index">
                {{index}}-{{char}}
            </li>
            <h2>测试遍历指定次数</h2>
            <li v-for="(number,index) of 5">
                {{index}}-{{number}}
            </li>

后两种用的较少
在这里插入图片描述

列表过滤

 <div id="id">
        <input type="text" v-model="search" placeholder="please input your name">
        <ul>
            <li v-for = "(p,index) in filPerson" :key="index">
                {{p.id}}-{{p.name}}-{{p.age}}
            </li>
        </ul>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                persons:[
                    {
                        id:'001',
                        name:'张三',
                        age:18
                    },
                    {
                        id:'002',
                        name:'李四',
                        age:20
                    },
                    {
                        id:'003',
                        name:'王五',
                        age:24
                    }                             
                ],
                filPerson:[],
                search:""
            },
            watch:{
                search:{
                    immediate:true,
                    handler(val){
                        this.filPerson =this.persons.filter(
                            (p)=>{
                                return p.name.indexOf(val) !== -1
                            }
                        )
                    }
                }
            }
            
        })
    </script>

watch监视器

computed:{
                filPerson(){
                    return this.persons.filter((p)=>{
                        return p.name.indexOf(this.search) !== -1
                    })
                }
            }
            
        })

优先使用computed

<div id="id">
        <input type="text" v-model="search" placeholder="please input your name">
        <ul>
            <li v-for = "(p,index) in filPerson" :key="index">
                {{p.id}}-{{p.name}}-{{p.age}}
            </li>
        </ul>
        <button @click="sortType = 2">升序</button>
        <button @click="sortType = 1">降序</button>
        <button @click="sortType = 0">原顺序</button>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:"#id",
            data:{
                persons:[
                    {
                        id:'001',
                        name:'张三',
                        age:18
                    },
                    {
                        id:'002',
                        name:'李四',
                        age:25
                    },
                    {
                        id:'003',
                        name:'王五',
                        age:24
                    }                             
                ],
                search:"",
                sortType:0//0 imply orginial
            },
        computed:{
                filPerson(){
                    const arr =  this.persons.filter((p)=>{
                        return p.name.indexOf(this.search) !== -1
                    })
                    if(this.sortType){
                        arr.sort((p1,p2)=>{ return this.sortType === 2? p1.age - p2.age : p2.age- p1.age})
                    }
                    return arr
                }
            }
            
        })
    </script>

列表排序

在这里插入图片描述
在这里插入图片描述

<div id="demo">
        <h3>student name{{student.name}}</h3>
        <h3>age:{{student.age}}</h3>
        <h3 v-if = "student.sex">{{student.sex}}</h3>
        <h3>hobby</h3>
        <ul>
            <li v-for="(h,index) in hobby" :keys = "index">
                {{h}}
            </li>
        </ul>
        <h3>friend</h3>
        <ul>
            <li v-for="(f,index) in friends" :keys = "index">
                {{f.name}}-{{f.age}}-{{f.sex}}
            </li>
        </ul>
        <button @click = "student.age++">made you age plus one</button>
        <button @click = "addSex">add a propty named sex,default:male </button>
        <button @click = "student.sex = 'unkown'">alter sex</button>
        <button @click = "addFriend">add a friend in the first place</button>
        <button @click = "updateFirstFriendName">update the first friend name is jack</button>
        <button @click = "addHobby">add a hobby</button>
        <button @click = "updateHobby">update first hobby to study</button>
    </div>
    <script text="text/javascript">
        Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示
        let vm = new Vue({
            el:'#demo',
            data:{
                student:{
                    name:'Denice',
                    age:18,
                },
                hobby:[
                    'smoke',
                    'drive',
                    'madeup'
                ],
                friends:[{
                    name:'eric',
                    age:13,
                    sex:'male'
                },
                {
                    name:'carols',
                    age:40,
                    sex:'male'
                },
                {
                    name:'mary',
                    age:30,
                    sex:'female'
                }                
                ]
            },
            methods: {
                addSex(){
                    Vue.set(this.student,'sex','male')
                },
                addFriend(){
                    this.friends.unshift({name:'jth',age:18,sex:"male"})
                },
                updateFirstFriendName(){
                    this.friends[0].name = 'jack'
                },
                addHobby(){
                    this.hobby.push('eat')
                },
                updateHobby(){
                    this.hobby.splice(0,1,'study')
                }


            },
        })  
    </script>

指令
可以查询vue的api

<div id="demo">
        <div>n的值是{{n}}</div>
        <div>十倍膨胀后的值<span v-big="n"></span></div>
        <input type="text" v-fbind="n">
        <button @click="n++">click me n plus one</button>
    </div>
    <script>
        new Vue({
            el:'#demo',
            data:{
                n:1
            },
            directives:{
                big(element,binding){
                    console.dir(element)
                    console.log(binding)
                    element.innerText = binding.value*10
                },
                fbind:{
                    bind(element,binding){
                        element.value = binding.value
                    },//将dom元素和结点值进行绑定
                    inserted(element,binding){
                        element.focus()
                    },//插入新增的dom元素
                    update(element,binding){
                        console.dir(element)
                        element.value = binding.value
                        element.focus()
                    }
                    
                }
            }
        })
    </script>

在这里插入图片描述
其中的三个回调函数不能写错,其为系统自带的函数,不能更改

生命周期

    <div id="demo">
        <div :style="{opacity}">hello world</div>
    </div>
    <script>
        new Vue({
            el:'#demo',
            data:{
                opacity:1
            },
            //vue完成模板的解析并把初始的真实dom元素放入页面后(挂载完毕)调用mounted
            mounted(){
                setInterval(()=>{
                    this.opacity-=0.01
                    if(this.opacity <= 0)this.opacity=1
                },16)
            },
        })
    </script>

mouted生命周期函数
在这里插入图片描述
this经过vue的处理指向vue的实例化对象
在这里插入图片描述
在这里插入图片描述

Vue组件的运用

实现局部功能代码和资源的集合
非单文件组件
一个文件包含n个组件
单文件组件
一个文件包含一个组件
创建

const student = Vue.extend({
data(){

return {}//data要用函数形式返回
})

注册
局部注册

    components:{
                student:student,
                compus:compus
            }

全局注册

 Vue.component('hello',hello)

使用

 <student></student>

使用组件标签

在这里插入图片描述
组件配置中的this指向VueComponents实例对象 简称vc
new Vue中的this指向vmVue实例对象
data(),watch,computed,methods

Vue脚手架

cls
创建脚手架 Vue.create vue_test
打开方式

npm run serve 

ctrl+c关闭脚手架
脚手架中的文件名不能随意更改
在这里插入图片描述
teminal中会展示自己的端口号8080

render函数

由于vue的阉割版,runtime版本去掉了三分之一的模板解析字段,当webpack进行打包时会减少消耗(vue.runtime.esm.js)

render(createElement){
	return createElement('h1','hello world')
}
render:h=>h{App}

ref属性

<template>
    <div>
        <h1 ref="demo">this is me</h1>
        <h2>name:{{name}}</h2>
        <h2>age:{{age}}</h2>
        <button @click="change">click me to chang your name</button>
    </div>
</template>

<script>
export default {
    name:'Student',
    data(){
        return{
            name:'jth',
            age:18
        }
    },
    methods: {
        change(){
            console.log(this.$refs.demo)//真实dom
        }
    },
}
</script>

<style>

</style>
组件实例对象 console.log(this.$refs.demo)//组件实例化对象 会输出component ## props配置
<Student/ name="Erics" :age="18">

v-bind会将age中转化为表达式,则会传入数字十八,而不是字符串十八

props:['name','age']//简单接受
props:{
	name:String,
	age:Number
}//接受的同时,对数据进类型限制
props:{
	name:{
		type:String,
		required:true//name是必须的
	},
	age{
		type:Number,
		default:99
	}
}

required:是否必须
default:加入没有传入值,规定默认值
default通常不和required一起用
外部传入的数据不允许更改,可在Vue工具上实验
可以更改,但会警告
可以设置一个中间变量
在这里插入图片描述

mixin(混入)

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

使用方式:

第一步定义混合:

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

}
第二步使用混入:

​ 全局混入:Vue.mixin(xxx)
​ 局部混入:mixins:[‘xxx’]

插件

功能:用于增强Vue

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

定义插件

对象.install = function (Vue, options) {
// 1. 添加全局过滤器
Vue.filter(…)

// 2. 添加全局指令
Vue.directive(....)

// 3. 配置全局混入(合)
Vue.mixin(....)

// 4. 添加实例方法
Vue.prototype.$myMethod = function () {...}
Vue.prototype.$myProperty = xxxx

}
使用插件:Vue.use()

scoped样式
作用:让样式在局部生效,防止冲突。
写法:

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

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

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

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

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

props适用于:

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

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

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

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

webStorage

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

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

相关API:

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

xxxxxStorage.getItem(‘person’);

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

xxxxxStorage.removeItem(‘key’);

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

xxxxxStorage.clear()

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

备注:

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

组件的自定义事件

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

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

绑定自定义事件:

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

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

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

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

触发自定义事件:

this.$emit('atguigu',数据)

解绑自定义事件this.$off('atguigu')
解绑多个自定义事件:this.$off(['atguigu','demo'])
不传参数为解绑所有的自定义事件

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

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

消息订阅与发布(pubsub)

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

使用步骤:

安装pubsub:npm i pubsub-js

引入: import pubsub from 'pubsub-js'

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

methods(){
  demo(data){......}
}
......
mounted() {
  this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
}

提供数据:pubsub.publish('xxx',数据)

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

nextTick

语法:this.$nextTick(回调函数)
作用:在下一次 DOM 更新结束后执行其指定的回调。
什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。
Vue封装的过度与动画
作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。

图示:

写法:

准备好样式:

元素进入的样式:
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>

备注:若有多个元素需要过度,则需要使用:,且每个元素都要指定key值。

插槽

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

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

使用方式:

默认插槽:

父组件中:

   <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组件决定)

具体编码:

父组件中:


```javascript
<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>

子组件中:
 

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

vuex

在这里插入图片描述

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

vue 会将代码中的import提升到代码的顶端

getters的使用

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

在store.js中追加getters配置

const getters = {
 bigSum(state){
  return state.sum * 10
	}
}

//创建并暴露store
export default new Vuex.Store({

	getters
})

组件中读取数据:$store.getters.bigSum

四个map方法的使用

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

import {mapActions,mapGetters,mapMutations,mapState} from 'vuex'

computed: {
//借助mapState生成计算属性:sum、school、subject(对象写法)
…mapState({sum:‘sum’,school:‘school’,subject:‘subject’}),

//借助mapState生成计算属性:sum、school、subject(数组写法)
...mapState(['sum','school','subject']),

},
mapGetters方法:用于帮助我们映射getters中的数据为计算属性

computed: {
//借助mapGetters生成计算属性:bigSum(对象写法)
…mapGetters({bigSum:‘bigSum’}),

//借助mapGetters生成计算属性:bigSum(数组写法)
...mapGetters(['bigSum'])

},
mapActions方法:用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数

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

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

}
mapMutations方法:用于帮助我们生成与mutations对话的方法,即:包含$store.commit(xxx)的函数

methods:{
//靠mapActions生成:increment、decrement(对象形式)
…mapMutations({increment:‘JIA’,decrement:‘JIAN’}),

//靠mapMutations生成:JIA、JIAN(对象形式)
...mapMutations(['JIA','JIAN']),

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

模块化+命名空间

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

修改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
  }
})

开启命名空间后,组件中读取state数据:

//方式一:自己直接读取

this.$store.state.personAbout.list

//方式二:借助mapState读取:

...mapState('countAbout',['sum','school','subject']),

开启命名空间后,组件中读取getters数据:

//方式一:自己直接读取

this.$store.getters['personAbout/firstPersonName']

//方式二:借助mapGetters读取:

...mapGetters('countAbout',['bigSum'])

开启命名空间后,组件中调用dispatch

//方式一:自己直接dispatch

this.$store.dispatch('personAbout/addPersonWang',person)

//方式二:借助mapActions:

...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

开启命名空间后,组件中调用commit

//方式一:自己直接commit

this.$store.commit('personAbout/ADD_PERSON',person)

//方式二:借助mapMutations:

...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),

路由

理解: 一个路由(route)就是一组映射关系(key - value),多个路由需要路由器(router)进行管理。
前端路由:key是路径,value是组件。
1.基本使用
安装vue-router,命令:npm i vue-router

应用插件:Vue.use(VueRouter)

编写router配置项:

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

指定展示位置

<router-view></router-view>

2.几个注意点

路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹。
通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
每个组件都有自己的 r o u t e 属性,里面存储着自己的路由信息。整个应用只有一个 r o u t e r ,可以通过组件的 route属性,里面存储着自己的路由信息。 整个应用只有一个router,可以通过组件的 route属性,里面存储着自己的路由信息。整个应用只有一个router,可以通过组件的router属性获取到。

3.多级路由(多级路由)

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

routes:[
	{
  path:'/about',
  component:About,
	},
	{
  path:'/home',
  component:Home,
  children:[ //通过children配置子级路由
			{
    path:'news', //此处一定不要写:/news
    component:News
			},
			{
    path:'message',//此处一定不要写:/message
    component:Message
			}
		]
	}
]

跳转(要写完整路径):

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

4.路由的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

5.命名路由

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

如何使用

给路由命名:

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

6.路由的params参数

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

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

传递参数

<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

7.路由的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
		}
	}
}

8.的replace属性

作用:控制路由跳转时操作浏览器历史记录的模式
浏览器的历史记录有两种写入方式:分别为push和replace,push是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
如何开启replace模式:<router-link replace …>News
9.编程式路由导航
作用:不借助 实现路由跳转,让路由跳转更加灵活

具体编码:

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

10.缓存路由组件

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

具体编码:

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

11.两个新的生命周期钩子

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

12.路由守卫

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

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

全局守卫:

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

独享守卫:

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

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

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

### Vue 前端日志记录与收集实现方案 在 Vue 项目中实现日志记录与收集是一项重要的功能,可以帮助开发者实时掌握应用运行状态、捕获异常以及优化用户体验。以下是基于现有引用内容和专业知识整理的解决方案。 #### 1. 路由模式下的日志配置 对于 Vue 的路由管理器 `vue-router`,可以通过设置不同的路由模式来决定日志记录的方式。如果采用的是 Hash 模式,则路径变化不会触发服务器请求;而 History 模式的路径变更会向服务器发送 GET 请求[^1]。因此,在初始化项目时可以定义如下参数: ```javascript const routerMode = 'History'; // 或者 'Hash' export default { mode: routerMode, log: true, // 是否开启日志打印 }; ``` 当 `log` 设置为 `true` 时,可以在控制台或者通过网络接口输出详细的导航信息。 #### 2. 利用第三方库增强日志能力 为了更全面地捕捉错误和其他重要事件,推荐引入专门用于前端监控的 SDK 如 **web-see** [^3]。此工具支持多种类型的监测需求,包括但不限于资源加载失败、JavaScript 错误处理、API 性能分析等。安装方式简单明了: ```bash npm install web-see --save ``` 接着按照官方文档完成基本配置即可开始使用其内置的功能模块。 #### 3. 结合业务逻辑自定义埋点策略 除了依赖外部插件外,还需要针对特定场景设计专属的数据采集机制——即所谓的“埋点”。根据实际应用场景的不同可以选择三种主要形式之一来进行操作:代码埋点、可视化埋点或是无痕埋点[^2]。其中最常见也是最容易上手的就是前者—直接修改源码添加必要的追踪语句。 例如监听按钮点击次数作为衡量用户活跃度的一个维度: ```html <template> <button @click="trackEvent('button_click')">Click Me</button> </template> <script> methods:{ trackEvent(eventName){ console.log(`User triggered event:${eventName}`); axios.post('/api/log', {event:eventName}); } } </script> ``` 上述例子展示了如何利用 Axios 库将发生的交互动作同步到后台数据库以便后续查询统计之用。 #### 4. 数据上传流程说明 最后一步就是确保所有的这些零散的信息能够被有效地传递给服务端加以保存和解析。一般有两种途径可供选择 —— 即刻提交或者是批量汇总后再统一发出 。考虑到网络状况等因素影响传输效率 ,后者往往更为合理些. 综上所述 ,以上便是关于怎样构建一套完整的 vue 平台上的客户行为跟踪体系的一些见解分享 . ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值