文章目录
- Vue是什么?
- Vue开发环境
- 分析Hello案例
- 模板语法
- 数据绑定
- el和data的两种写法
- 理解MVVM
- Object.defineProperty
- 理解数据代理
- Vue中的数据代理
- 事件处理
- 事件修饰符
- 键盘事件
- 事件总结
- 姓名案例
- 计算属性_简写
- 天气案例
- 监视属性(侦听属性)
- 深度监视
- 监视的简写形式
- watch对比computed
- 绑定class样式
- 绑定style样式
- 条件渲染
- 列表渲染
- key的作用与原理
- 列表过滤
- 列表排序
- 更新小问题
- Vue检测数据的原理_对象
- Vue.set()
- Vue检测数据的原理_数组
- 收集form
- 过滤器
- 内置指令
- 自定义指令_函数式
- 生命周期
- Vue组件化编程
- 使用Vue脚手架
- Vue中的ajax
- vuex
- vue-router路由
- Vue UI组件库
Vue是什么?
一套用于构建用户界面的渐进式JavaScript框架
渐进式: Vue可以自底向上逐层的应用
简单应用: 只需一个轻量小巧的核心库
复杂应用: 可以引入各式各样的Vue插件
vue的特点
- 采用组件化模式,提高代码复用率、且让代码更好维护。
- 声明式编码,让编码人员无需直接操作DOM,提高开发效率。
Vue开发环境
关闭生产提示:
Vue.config.productionTip=false;
初识Vue:
- 想让Vue工作,就必须创建一个Vue实例,且要传入一个配置对象;
- root容器里的代码依然符合html规范,只不过混入看一些特殊的Vue语法;
- root容器里的代码被称为[Vue模板]
<!-- 准备好一个容器 -->
<div id="root">
<h1>Hello,{{name}}</h1>
</div>
<script>
Vue.config.productionTip=false;
//创建Vue实例
const vm = new Vue({
el: '#root',
//el用于指定当前Vue实例为哪个容器服务,
//值通常为css选择器字符串。
data:{
//data中用于存储数据,数据供el所指定的容器去使用。
//值我们暂时先写成一个对象。
name:'xxx'
}
})
</script>
分析Hello案例
容器------Vue实例 1对1
注意区分: JS表达式(一种特殊的JS代码) 和 JS代码(语句)
- 表达式: 一个表达式会产生一个值,可以放在任何一个需要值的地方;
- 变量a
- 变量a+b
- demo(1)
- x===y ? ‘a’:‘b’
- js代码(语句)
- if(){}
- for(){}
-----根
<!-- 准备好一个容器 -->
<div id="root">
<h1>Hello,{{name.toUpperCase()}} 1</h1>
<h1>Hello,{{name}} 2</h1>
</div>
<script>
Vue.config.productionTip=false;
//创建Vue实例
const vm = new Vue({
el: '#root',
//el用于指定当前Vue实例为哪个容器服务,
//值通常为css选择器字符串。
data:{
//data中用于存储数据,数据供el所指定的容器去使用。
//值我们暂时先写成一个对象。
name:'xxx'
}
})
真实开发中只有一个Vue实例,并且会配合着组件一起使用;
- {{xxx}}中的xxx要写js表达式,且xxx可以自动读取到data中所有的属性;
- 一旦data中的数据发生改变,那么页面中用到该数据的地方也会自动更新;
模板语法
v-bind:
=简写=> :
Vue模板语法有2大类:
1、插值语法:
- 功能:用于解析标签体内容
- 写法: {{xxx}},xxx是js表达式,且可以直接读取到data中所有属性。
2、指令语法:
- 功能: 用于解析标签(包括: 标签属性、标签体内容、绑定事件…)
- 举例: v-bind:href=“xxx” 或 简写为
:href="xxx"
,xxx同样要写js表达式且可以直接读取到data中所有的属性。 - 备注: Vue中有很多指令。且形式都是v-???,此处我们只是拿v-bind举个例子。
<!-- 准备好一个容器 -->
<div id="root">
<h1>插值语法</h1>
<h3>你好,{{name}}</h3>
<hr/>
<h1>指令语法</h1>
<a v-bind:href="school.url">{{school.name}}1</a>
<a :href="school.url">百度2</a>
</div>
<script>
Vue.config.productionTip=false;
//创建Vue实例
const vm = new Vue({
el: '#root',
//el用于指定当前Vue实例为哪个容器服务,
//值通常为css选择器字符串。
data:{
//data中用于存储数据,数据供el所指定的容器去使用。
//值我们暂时先写成一个对象。
name:'jack',
school: {
name: '百度',
url: 'http://www.baidu.com'
}
}
})
数据绑定
Vue有两种数据绑定的方式:
- 单向绑定(v-bind): 数据只能从data流向页面。
- 双向绑定(v-model): 数据不仅能从data流向页面。还可以从页面流向data
- 备注:
- 双向绑定一般都应用在表单类元素上(如: input、select等)
- v-model: value可以简写为v-model,因为v-model默认收集的就是value值。
<!-- 准备好一个容器 -->
<div id="root">
<!-- 普通写法 -->
单向数据绑定:<input type="text" v-bind:value="name"/><br/>
双向数据绑定:<input type="text" v-model:value="name"/><br/>
<!-- 简写 -->
单向数据绑定:<input type="text" :value="name"/><br/>
双向数据绑定:<input type="text" v-model="name"/><br/>
<!-- 如下代码是错误的,因为v-model只能应用在表单类元素上(输入类元素) -->
<!-- <h2 v-model:x="name">你好呀</h2> -->
</div>
<script>
Vue.config.productionTip=false;
//创建Vue实例
const vm = new Vue({
el: '#root',
//el用于指定当前Vue实例为哪个容器服务,
//值通常为css选择器字符串。
data:{
//data中用于存储数据,数据供el所指定的容器去使用。
//值我们暂时先写成一个对象。
name:'尚硅谷',
}
})
</script>
el和data的两种写法
data与el的2种写法
-
el有2种写法
- new Vue时候配置el属性
- 先创建Vue实例,随后再通过vm.$mount(’#root’)指定el的值
-
data有两种写法
- 对象式
- 函数式
如何选择:目前哪种写法都可以,以后学习到组件时,data必须使用函数式,否则会报错。
-
一个重要的原则:
- 由Vue管理的函数,一定不要写箭头函数,一旦写了箭头函数,this就不再是Vue实例了。
<!-- 准备好一个容器 -->
<div id="root">
<h1>你好,{{name}}</h1>
</div>
<script>
Vue.config.productionTip=false;
// //el的两种写法
// const v = new Vue({
// // el:'#root',//第一种写法
// data:{
// name:'尚硅谷'
// }
// })
// console.log(v);
// setTimeout(()=>{
// v.$mount('#root');//第二种写法
// },1000)
new Vue({
el:'#root',
//data的第一种写法:对象式
// data:{
// name:'尚硅谷'
// }
//data的第二种写法:函数式
// data:()=>{//不可以写成箭头函数
// console.log('@',this);//此处的this是windows
// return {
// name:'尚硅谷'
// }
// }
data(){
console.log('@',this);//此处的this是vue实例对象
return {
name:'尚硅谷'
}
}
})
</script>
理解MVVM
1、M:模型(Model):对应data中的数据
2、V:视图(View): 模板
3、VM: 视图模型(ViewModel): Vue实例对象
观察发现:
- data中所有的属性,最后都出现在了vm身上。
- vm身上所有的属性 及 Vue原型上所有属性,在Vue模板中都可以直接使用。
Object.defineProperty
<script>
let number = 18;
let person= {
name: '张三',
sex: '男'
}
Object.defineProperty(person,'age',{
// value:18,
// enumerable:true,//控制属性是否可以枚举,默认值是false
// writable:true,//控制属性是否可以修改,默认值是false
// configurable:true//控制属性是否可以删除,默认值是false
//当有人读取person的age属性时,get函数(getter)就会被调用,且返回值就是age的值
get:function(){
return number;
},
//当有人修改person的age属性时,set函数(setter)就会被调用,且会收到修改的具体值
set(value){
console.log('值是',value);
number=value;
}
})
console.log(person)
</script>
理解数据代理
数据代理:
- 通过一个对象代理对另一个对象中属性的操作:(读/写):
–>
<script>
let obj = {
x:100
}
let obj2 = {
y:200
}
Object.defineProperty(obj2,'x',{
get(){
return obj.x
},
set(value){
obj.x = value
}
})
</script>
Vue中的数据代理
- Vue中的数据代理:
- 通过vm对象来代理data对象中属性的操作:(读/写)
- Vue中数据代理的好处:
- 更加方便的操作data中的数据
- 基本原理
- 通过Object.defineProperty()把data对象中所有属性添加到vm上
- 为每一个添加到vm上的属性,都指定一个getter/setter
- 在getter/setter内部去操作(读/写)data中对应的属性。
事件处理
事件的基本使用:
-
使用v-on: xxx 或@xxx 绑定事件,其中xxx是事件名;
-
事件的回调需要配置在methods对象中,最终会在vm上;
-
methods中配置的函数,不要用箭头函数!否则this就不是vm了;
-
methods中配置的函数,都是被Vue所管理的函数,this的指向是vm 或 组件实例对象
-
@click=“demo” 和 @click=“demo($event)” 效果一致,但后者可以传参;
<!-- 准备好一个容器 -->
<div id="root">
<h2>欢迎来到{{name}}学习</h2>
<button v-on:click="showInfo1">点我提示信息1(不传参)</button>
<button @click="showInfo2(66,$event)">点我提示信息2(传参)</button>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
name: '尚硅谷',
address: '北京'
},
methods: {
showInfo1(event){
// console.log(event.target.innerText);
//console.log(this); //此处的this是vm
alert('同学你好');
},
showInfo2(number,event){
console.log(number,event);
// console.log(event.target.innerText);
//console.log(this); //此处的this是vm
//alert('同学你好!!');
}
}
})
</script>
事件修饰符
Vue中的事件修饰符:
- prevent:阻止默认事件(常用):
- stop: 阻止事件冒泡(常用):
- once: 事件只触发一次(常用);
- capture: 使用事件的捕获模式;
- self: 只有event.target是当前操作的元素时才触发事件;
- passive: 事件的默认行为立即执行,无需等待事件回调执行完毕;
<!-- 引入Vue -->
<script src="../js/vue.js"></script>
<style>
* {
margin-top: 20px;
}
.demo1 {
height: 50px;
background-color: skyblue;
}
.box1 {
padding: 5px;
background-color: skyblue;
}
.box2 {
padding: 5px;
background-color: orange;
}
.list {
width: 200px;
height: 200px;
background-color: peru;
overflow: auto;
}
li {
height: 100px;
}
</style>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<h2>欢迎来到{{name}}学习</h2>
<!-- <a href="www.baidu.com" @click="showInfo">跳转</a> -->
<!-- 阻止默认事件(常用) -->
<a href="www.baidu.com" @click.prevent="showInfo">跳转</a>
<!-- 阻止事件冒泡(常用) -->
<div class="demo1" @click="showInfo">
<button @click.stop="showInfo">点我提示信息</button>
</div>
<!-- 事件只触发一次(常用) -->
<button @click.once="showInfo">点我提示信息</button>
<!-- 使用事件的捕获模式 : 先捕获再冒泡-->
<div class="box1" @click.capture="showMsg(1)">
div1
<div class="box2" @click="showMsg(2)">
div2
</div>
</div>
<!-- 只有event.target是当前操作的元素时才触发事件; -->
<div class="demo1" @click.self="showInfo">
<button @click="showInfo">点我提示信息</button>
</div>
<!-- 事件的默认行为立即执行,无需等待事件回调执行完毕; -->
<!-- @scroll="demo" -->
<!-- @wheel="demo" 滚轮 -->
<ul @wheel.passive="demo" class="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
name: '尚硅谷',
address: '北京'
},
methods: {
showInfo(e){
// e.stopPropagation();
// e.preventDefault();//阻止默认事件
// alert('取消跳转');
console.log(e.target);
},
showMsg(msg){
console.log(msg);
},
demo(){
for(let i = 0;i<100000;i++){
console.log('#');
}
console.log('累坏了')
}
}
})
</script>
键盘事件
-
Vue中常用的按键别名:
- 回车 => enter
- 删除 => delete(捕获“删除”和“退格”键)
- 退出 => esc
- 空格 => space
- 换行 => tab(特殊,必须配合keydown去使用)
- 上 => up
- 下 => down
- 左 => left
- 右 => right
-
Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名)
-
系统修饰键(用法特殊): ctrl、alt、shift、meta
- 配合keyup使用:按下修饰键的同时,再按下其它键,随后释放其它键,事件才被触发。
- 配合keydown使用: 正常触发事件。
-
也可以使用keyCode去指定具体的按键(不推荐)
-
Vue.config.keyCodes.自定义键名=键码。可以去定制按键别名
<!-- 准备好一个容器 -->
<div id="root">
<h2>欢迎来到{{name}}学习</h2>
<input type="text" placeholder="按下回车提示输入" @keyup.13="showInfo"/>
<!-- @keyup.enter="showInfo" @keyup.caps-lock="showInfo" @keyup.13="showInfo" -->
</div>
<script>
Vue.config.productionTip=false;
Vue.config.keyCodes.huiche=13;//定义了一个别名按键
const vm = new Vue({
el:'#root',
data: {
name: '尚硅谷',
address: '北京'
},
methods: {
showInfo(e) {
//console.log(e.key,e.keyCode);//CapsLock 20
// if(e.keyCode !==13)return
console.log(e.target.value);
}
}
})
</script>
事件总结
- 修饰符可以连续写
@keyup.ctrl.y:摁ctrl+y才会生效!
姓名案例
插值语法实现
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model="firstName"/><br/>
名:<input type="text" v-model="lastName"/><br/>
全名:<span>{{firstName.slice(0,3)}}-{{lastName}}</span>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
firstName: '张',
lastName: '三'
}
})
</script>
使用methods实现
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model="firstName"/><br/>
名:<input type="text" v-model="lastName"/><br/>
全名:<span>{{fullName()}}</span>
<!-- 加()代表使用方法的返回值,不加()表示将函数放在此处! -->
<!-- data中的属性一旦发生变化,模板重新解析!遇到插值里是方法,方法重新调用! -->
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
firstName: '张',
lastName: '三'
},
methods: {
fullName(){
return this.firstName+'-'+this.lastName;
}
}
})
</script>
计算属性实现
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model="firstName"/><br/>
名:<input type="text" v-model="lastName"/><br/>
全名:<span>{{fullName}}</span>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
firstName: '张',
lastName: '三'
},
computed: {
fullName: {
/*
get有什么作用?当有人读取fullName时,
get就会被调用,且返回值就作为fullName的值
get什么时候调用?
1、初次读取fullName时。
2、所依赖的数据发生变化时。
*/
get(){
return this.firstName+'-'+this.lastName;
},
//set什么时候调用?
//当fullName被修改时
set(value){
const arr = value.split('-');
this.firstName = arr[0];
this.lastName = arr[1];
}
}
}
})
</script>
计算属性:
- 定义: 要用的属性不存在,要通过已有属性计算得来
- 原理:底层借助了Object.defineproperty方法提供的getter和setter
- get函数什么时候执行?
- 初次读取时会执行一次
- 当依赖的数据发生改变时会被再次调用
- 优势: 与methods实现相比,内部有缓存机制(复用),效率更高,调试方便。
- 备注
- 计算属性最终会出现在vm上,直接读取使用即可。
- 如果计算属性要被修改,那必须写set函数去相应修改,且set中要引起计算时依赖的数据发生改变。
计算属性_简写
只考虑使用get时
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model="firstName"/><br/>
名:<input type="text" v-model="lastName"/><br/>
全名:<span>{{fullName}}</span>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
firstName: '张',
lastName: '三'
},
computed: {
//简写只考虑读取不考虑修改---当get用
fullName(){
return this.firstName+'-'+this.lastName;
}
}
})
</script>
天气案例
用学过的知识实现
<!-- 准备好一个容器 -->
<div id="root">
<h2>今天天气很{{info}}</h2>
<!-- isHot?'炎热':'凉爽' -->
<button @click="changeWeather">切换天气</button>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
isHot: true
},
computed: {
info(){
return this.isHot?'炎热':'凉爽';
}
},
methods: {
changeWeather(){
this.isHot=!this.isHot;
}
}
})
</script>
如果容器中没有使用我们定义的属性,浏览器的vue工具就不会更新数据了。我们更改属性。实际依然改变。但是浏览器的vue工具不会显示!
<button @click="isHot=!isHot">切换天气</button>
绑定事件的时候: @xxx=“yyy” yyy可以写一些简单的语句
下面不推荐这样使用!
<div id="root">
<h2>今天天气很{{info}}</h2>
<!-- isHot?'炎热':'凉爽' -->
<button @click="window.alert(1)">切换天气</button>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
isHot: true,
window
},
监视属性(侦听属性)
<!-- 准备好一个容器 -->
<div id="root">
<h2>今天天气很{{info}}.</h2>
<!-- isHot?'炎热':'凉爽' -->
<button @click="changeWeather">切换天气</button>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
isHot: true
},
computed: {
info(){
return this.isHot?'炎热':'凉爽';
}
},
methods: {
changeWeather(){
this.isHot=!this.isHot;
}
},
watch:{
isHot:{
immediate:false,//初始化时让handler调用一下
//handler什么时候调用?
//当isHot发生改变时。
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue);
}
}
}
})
/*
vm.$watch('isHot',{
immediate:false,//初始化时让handler调用一下
//handler什么时候调用?
//当isHot发生改变时。
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue);
}
})
*/
</script>
监视属性watch:
- 当被监视的属性变化时,回调函数自动调用,进行相关操作
- 监视的属性必须存在,才能进行监视!!
- 监视的两种写法:
- new Vue时传入watch配置
- 通过vm.$watch监视
深度监视
<!-- 准备好一个容器 -->
<div id="root">
<h2>今天天气很{{info}}.</h2>
<!-- isHot?'炎热':'凉爽' -->
<button @click="changeWeather">切换天气</button>
<hr/>
<h3>a的值是:{{numbers.a}}</h3>
<button @click="numbers.a++">点我让a+1</button>
<h3>b的值是:{{numbers.b}}</h3>
<button @click="numbers.b++">点我让b+1</button>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
isHot: true,
numbers: {
a:1,
b:1
}
},
computed: {
info(){
return this.isHot?'炎热':'凉爽';
}
},
methods: {
changeWeather(){
this.isHot=!this.isHot;
}
},
watch:{
isHot:{
handler(newValue,oldValue){
console.log('isHot被修改了',newValue,oldValue);
}
},
//监视多级结构中某个属性的变化
/*'numbers.a':{
handler(){
console.log('a被修改了');
}
}
*/
//监视多级结构中所有属性的变化
numbers:{
deep:true,
handler(){
console.log('numbers被修改了');
}
}
}
})
</script>
深度监视:
- Vue中的watch默认不监测对象内部值的改变(一层)
- 配置deep:true可以监测对象内部值改变(多层)
备注:
- Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以!
- 使用watch时根据数据的具体结构,决定是否采用深度监视。
监视的简写形式
<!-- 准备好一个容器 -->
<div id="root">
<h2>今天天气很{{info}}.</h2>
<!-- isHot?'炎热':'凉爽' -->
<button @click="changeWeather">切换天气</button>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
isHot: true,
},
computed: {
info(){
return this.isHot?'炎热':'凉爽';
}
},
methods: {
changeWeather(){
this.isHot=!this.isHot;
}
},
watch:{
//正常写法
// isHot:{
// // immediate: true,//初始化时让handler调用一下
// //deep: true,//深度监视
// 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>
watch对比computed
computed和watch之间的区别:
- computed能完成的功能,watch都可以完成
- watch能完成的功能,computed不一定能完成,例如:watch可以进行异步操作
两个重要的小原则:
- 所被Vue管理的函数,最好写成普通函数,这样this的指向才是vm或组件实例对象。
- 所有不被Vue管理的函数(定时器的回调函数、ajax的回调函数、Promise的回调函数等),最好写成箭头函数,这样this的指向才是vm或组件实例对象。
<body>
<!-- 准备好一个容器 -->
<div id="root">
姓:<input type="text" v-model="firstName"/><br/>
名:<input type="text" v-model="lastName"/><br/>
全名:<span>{{fullName}}</span>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
firstName: '张',
lastName: '三',
fullName:'张-三'
},
watch: {
firstName(val){
setTimeout(()=>{
this.fullName = val+"-"+this.lastName;
},1000)
},
lastName(val){
this.fullName = this.firstName+"-"+val;
}
}
})
</script>
绑定class样式
绑定class样式—字符串写法
适用于: 样式的类名不确定,需要动态指定
:class="mood"
mood:'noemal'
Math.floor(Math.random()*3)
向下取整012
绑定class样式—数组写法
适用于: 要绑定的样式个数不确定,名字也不确定
vm.arr.shift()
移除数组中的第一个元素
vm.arr.push()
:class="['aa','bb']"
绑定class样式—对象写法
适用于: 要绑定的样式个数确定,名字也确定,但要动态决定用不用
:class="classObj"
classObj:{
aaa: false
}
绑定style样式
绑定style样式,对象写法
:style="{fontSize:fsize+'px';}"
:style="styleObj"
styleObj:{
fontSize: '40px'}
styleObj:{
fontSize:'40px',
color:'red',
backgroundColor:'orange'
}
绑定style样式,数组写法
:style="[styleObj,styleObj2]"
绑定样式:
- class样式
- class=“xxx” xxx可以是字符串、对象、数组、
- 字符串写法适用于: 类名不确定,要动态获取。
- 对象写法适用于: 要绑定多个样式,个数不确定,名字也不确定
- 数组写法适用于:要绑定多个样式,个数确定,名字也确定,但是不确定用不用
- style样式
- :style="{fontSize:xxx}"其中xxx是动态值
- :style="[a,b]"其中a、b是样式对象。
条件渲染
v-if
v-else-if
参照 if与elseif 而且不允许被打断!(隔开)
v-else后面不要写条件!!!!!
结构被破坏
<div>
<h2>xxx</h2>
</div>
结构未被破坏!(template:模板)且只能配合v-if
使用
<template v-if="n===1">
<h2>xxx</h2>
</template>
条件渲染:
v-if
写法
-
v-if=“表达式”
-
v-else-if=“表达式”
-
v-else=“表达式”
-
适用于: 切换频率较低的场景
-
特点: 不展示的DOM元素直接被移除
-
注意: v-if可以和: v-else-if、v-else一起使用,但要求结构不能被"打断"
v-show
- 写法: v-show=“表达式”
- 适用于: 切换频率较高的场景
- 特点: 不展示的DOM元素未被移除,仅仅是使用样式隐藏掉
备注: 使用v-if时,元素可能无法获取到,而使用v-show一定可以获取到。
列表渲染
v-for指令:
- 用于展示列表数据
- 语法: v-for="(item,index) in xxx" :key=“yyy”
- 可遍历:数组、对象、字符串(用的很少)、指定次数(用的很少)
<!-- 准备好一个容器 -->
<div id="root">
<!--遍历数组:用的最多! -->
<ul>
<li v-for="p in persons" :key="p.id">
{{p.id}}-{{p.name}}-{{p.age}}
</li>
</ul>
<ul>
<li v-for="(p,index) in persons" :key="index">
{{p.name}}-{{p.age}}
</li>
</ul>
<ul>
<li v-for="(p,index) of persons" :key="index">
{{p.name}}-{{p.age}}
</li>
</ul>
<!-- 遍历对象 -->
<ul>
<li v-for="(value,key) of car" :key="key">
{{key}}-{{value}}
</li>
</ul>
<!-- 遍历字符串 -->
<ul>
<li v-for="(char,index) of str" :key="index">
{{char}}-{{index}}
</li>
</ul>
<!-- 遍历次数 -->
<ul>
<li v-for="(number,index) of 5" :key="index">
{{number}}-{{index}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
persons: [
{id:'001',name:'张三',age:18},
{id:'002',name:'李四',age:19},
{id:'003',name:'王五',age:20}
],
car:{
name: '奥迪',
price: '70万',
color: '黑色'
},
str:'hello'
}
})
</script>
key的作用与原理
diff 对比
面试题:
react、vue中的key有什么作用?(key的内部原理)
- 虚拟DOM中key的作用:
- key是虚拟DOM对象的标识,当状态中的数据发生变化时,Vue会根据[新数据]生成[新的虚拟DOM],随后Vue进行[新虚拟DOM]与[旧虚拟DOM]的差异比较,比较规则如下:
- 对比规则:
- 旧虚拟DOM中找到了与新虚拟DOM相同的key:
- 若虚拟DOM中内容没变,直接使用之前的真实DOM!
- 若虚拟DOM中内容变了,则生成新的真实DOM,随后替换掉页面中之前的真实DOM。
- 旧虚拟DOM中未找到与新虚拟DOM相同的key
- 创建新的真实DOM,随后渲染到页面
- 旧虚拟DOM中找到了与新虚拟DOM相同的key:
- 用index作为key可能会引发的问题:
- 若对数据进行: 逆序添加、逆序删除等破坏顺序操作:
- 会产生没有必要的真实DOM更新==>界面效果没问题,但效率低
- 如果结构中还包含输入类的DOM:
- 会产生错误DOM更新==>界面有问题。
- 若对数据进行: 逆序添加、逆序删除等破坏顺序操作:
- 开发中如何选择key?:
- 最好使用每条数据的唯一标识为key,比如id、手机号、身份证号、学号等唯一值。
- 如果不存在对数据的逆序添加、逆序删除等破坏顺序操作,仅用于渲染列表用于展示,使用index作为key是没有问题的。
<!-- 准备好一个容器 -->
<div id="root">
<!--遍历数组:用的最多! -->
<button @click.once="add">添加</button>
<ul>
<!-- key被vue使用 -->
<li v-for="(p,index) of persons" :key="p.id">
{{p.name}}-{{p.age}}
<input type="text"/>
</li>
</ul>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
persons: [
{id:'001',name:'张三',age:18},
{id:'002',name:'李四',age:19},
{id:'003',name:'王五',age:20}
]
},
methods:{
add(){
const p = {id:'004',name:'刘星',age:'40'};
this.persons.unshift(p);//添加到第一个
}
}
})
</script>
列表过滤
watch实现:
<div id="root">
<h2>人员列表</h2>
<input type="text" placeholder="请输入名字" v-model="keyWord"/>
<ul>
<!-- key被vue使用 -->
<li v-for="(p,index) of filPersons" :key="index">
{{p.name}}-{{p.age}}-{{p.sex}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
keyWord: '',
persons: [
{id:'001',name:'马冬梅',age:18,sex:"女"},
{id:'002',name:'周冬雨',age:19,sex:"女"},
{id:'003',name:'周杰伦',age:20,sex:"男"},
{id:'004',name:'温兆伦',age:21,sex:"男"}
],
filPersons: []
},
//watch实现
watch:{
keyWord:{
immediate: true,
handler(val){
this.filPersons = this.persons.filter((p)=>{
return p.name.indexOf(val) !== -1;
})
}
}
}
})
</script>
计算属性实现
<!-- 准备好一个容器 -->
<div id="root">
<h2>人员列表</h2>
<input type="text" placeholder="请输入名字" v-model="keyWord"/>
<ul>
<!-- key被vue使用 -->
<li v-for="(p,index) of filPersons" :key="index">
{{p.name}}-{{p.age}}-{{p.sex}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip=false;
//#region 在此处折叠
/*
const vm = new Vue({
el:'#root',
data: {
keyWord: '',
persons: [
{id:'001',name:'马冬梅',age:18,sex:"女"},
{id:'002',name:'周冬雨',age:19,sex:"女"},
{id:'003',name:'周杰伦',age:20,sex:"男"},
{id:'004',name:'温兆伦',age:21,sex:"男"}
],
filPersons: []
},
//watch实现
watch:{
keyWord:{
immediate: true,
handler(val){
this.filPersons = this.persons.filter((p)=>{
return p.name.indexOf(val) !== -1;
})
}
}
}
})
*/
//#endregion
const vm = new Vue({
el:'#root',
data: {
keyWord: '',
persons: [
{id:'001',name:'马冬梅',age:18,sex:"女"},
{id:'002',name:'周冬雨',age:19,sex:"女"},
{id:'003',name:'周杰伦',age:20,sex:"男"},
{id:'004',name:'温兆伦',age:21,sex:"男"}
]
},
computed:{
filPersons(){
return this.persons.filter((p)=>{
return p.name.indexOf(this.keyWord) !== -1;
})
}
}
})
</script>
#region 在此处折叠
列表排序
<!-- 准备好一个容器 -->
<div id="root">
<h2>人员列表</h2>
<input type="text" placeholder="请输入名字" v-model="keyWord"/>
<button @click="sortType = 2" >年龄升序</button>
<button @click="sortType = 1" >年龄降序</button>
<button @click="sortType = 0" >原顺序</button>
<ul>
<!-- key被vue使用 -->
<li v-for="(p,index) of filPersons" :key="index">
{{p.name}}-{{p.age}}-{{p.sex}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
keyWord: '',
sortType: 0,//0原顺序 1降序 2升序
persons: [
{id:'001',name:'马冬梅',age:18,sex:"女"},
{id:'002',name:'周冬雨',age:19,sex:"女"},
{id:'003',name:'周杰伦',age:20,sex:"男"},
{id:'004',name:'温兆伦',age:21,sex:"男"}
]
},
computed:{
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>
更新小问题
<!-- 准备好一个容器 -->
<div id="root">
<h2>人员列表</h2>
<button @click="updatemei">更新</button>
<ul>
<!-- key被vue使用 -->
<li v-for="(p,index) of persons" :key="p.id">
{{p.name}}-{{p.age}}-{{p.sex}}
</li>
</ul>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
persons: [
{id:'001',name:'马冬梅',age:18,sex:"女"},
{id:'002',name:'周冬雨',age:19,sex:"女"},
{id:'003',name:'周杰伦',age:20,sex:"男"},
{id:'004',name:'温兆伦',age:21,sex:"男"}
]
},
methods: {
updatemei(){
// this.persons[0].name='马老师'//奏效
// this.persons[0].age='50'//奏效
// this.persons[0].sex='男'//奏效
this.persons[0] = {id:'001',name:'马老师',age:'50'};
}
}
})
</script>
更改对象,点击后页面却没改,为什么?
Vue检测数据的原理_对象
Vue.set()
Vue.set(target,key,val)
Vue.set(vm._data.student.‘sex’,‘男’);
vm.$set(vm._data.student.‘sex’,‘男’);
Vue.set(vm.student,‘sex’,‘男’)
Vue检测数据的原理_数组
push
pop
shift
unshift
splice
sort
reverse
vm._data.student.hobby.push(‘学习’)添加
vm._data.student.hobby.shift()删除第一个
vm._data.student.hobby.splice(0,1,‘学习’)替换第一个
arr.push === Array.prototype.push
true
vm._data.student.hobby.push === Array.prototype.push
false
修改第一个,不要用索引值
this.student.hobby.splice(0,1,'开车');
改为
Vue.set(this.student.hbby,0,'开车')
this.$set(this.student.hbby,0,'开车')
Vue监视数据的原理:
-
vue会监视data中所有层次的数据
-
如何检测对象中的数据?
- 通过setter实现监视,且要在new Vue时就传入要检测的数据
- 对象中后追加的属性,Vue默认不做响应式处理
- 如需给后添加的属性做响应式,请使用如下API:
- Vue.set(target,propertyName/index,value)
- vm.$set(target,propertyName/index,value)
- 通过setter实现监视,且要在new Vue时就传入要检测的数据
-
如何检测数组中的数据?
- 通过包裹数组更新元素的方法实现,本质就是做了两件事:
- 调用原生对应的方法对数组进行更新
- 重新解析模板,进而更新页面
- 通过包裹数组更新元素的方法实现,本质就是做了两件事:
-
在Vue修改数组中某个元素一定要用如下方法:
- 使用这些API: push()、pop()、shift()、unshift()、splice()、sort()、reverse()
- Vue.set()或vm.$set()
特别注意: Vue.set() 和 vm.$set()不能给vm或vm的根数据对象vm._data
添加属性!!!
收集form
<!-- 准备好一个容器 -->
<div id="root">
<form @submit.prevent="demo" >
用户名:
<input type="text" v-model.trim="userInfo.account"><br/>
密码:
<input type="password" v-model="userInfo.password"><br/>
年龄:
<input type="number" v-model.number="userInfo.age"><br/>
性别:
男<input type="radio" name="sex" v-model="userInfo.sex" value="male">
女<input type="radio" name="sex" v-model="userInfo.sex" value="female"><br/>
爱好:
学习<input type="checkbox" v-model="userInfo.hobby" value="study">
吃饭<input type="checkbox" v-model="userInfo.hobby" value="eat">
打游戏<input type="checkbox" v-model="userInfo.hobby" value="game"><br/>
所属校区
<select v-model="userInfo.city">
<option value="">请选择校区</option>
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="shenzhen">深圳</option>
<option value="wuhan">武汉</option>
</select><br/>
其它信息:
<textarea v-model.lazy="userInfo.other"></textarea><br/>
<input type="checkbox" v-model="userInfo.agree">
阅读并接受<a href="#">《用户协议》</a><br/>
<button>提交</button>
</form>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
userInfo: {
account: '',
password: '',
sex: '',
hobby: [],
city: '',
other: '',
agree: ''
}
},
methods: {
demo(){
console.log(JSON.stringify(this.userInfo));
}
}
})
</script>
收集表单数据:
若<input type="text"/>
则v-model收集的是value值,用户输入的就是calue值
若<input type="radio/>"
则v-model收集的是value值,且要给标签配置value值
若<input type="checkbox />"
- 没有配置input的value属性,那么收集的就是checked(勾选 or 未勾选,是布尔值)
- 配置input的value属性:
- v-model的初始值是非数组,那么收集的就是checked(勾选 or 未勾选,是布尔值)
- v-model的初始值是数组,那么收集的就是value组成的数组
- 备注: v-model的三个修饰符
- lazy:失去焦点再收集数据
- number: 输入字符串转为有效的数字
- trim: 输入首位空格过滤
过滤器
BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务
<!-- 引入Vue -->
<script src="../js/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.10.6/dayjs.min.js"></script>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<h2>显示格式化后的时间</h2>
<!-- 计算属性方法 -->
<h3>现在是:{{fmtTime}}</h3>
<!-- methods实现 -->
<h3>现在是:{{getFmtTime()}}</h3>
<!-- 过滤器实现 -->
<h3>现在是:{{time | timeFormater}}</h3>
<!-- 过滤器实现 (传参)-->
<h3>现在是:{{time | timeFormater('YYYY年MM月DD日 hh:mm:ss') | mySlice}}</h3>
<h3 :x="msg | mySlice">尚硅谷</h3>
</div>
<div id="root2">
<h2>{{msg | mySlice}}</h2>
</div>
<script>
Vue.config.productionTip=false;
Vue.filter('mySlice',function(value){
return value.slice(0,5);
})
const vm = new Vue({
el:'#root',
data: {
time:1621561377603,
msg:'hello!!!!!!'
},
computed: {
fmtTime(){
return dayjs(this.time).format('YYYY-MM-DD hh:mm:ss');
}
},
methods: {
getFmtTime(){
return dayjs(this.time).format('YYYY-MM-DD hh:mm:ss');
}
},
//局部过滤器
filters: {
timeFormater(value,str='YYYY-MM-DD hh:mm:ss'){
return dayjs(value).format(str);
},
// mySlice(value){
// return value.slice(0,4);
// }
}
})
new Vue({
el:'#root2',
data:{
msg:'hello,atguigu!'
}
})
</script>
过滤器:
-
定义:对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)
-
语法:
- 注册过滤器: Vue.filter(name,callback) 或 new Vue{filters:{}}
- 使用过滤器: {{xxx | 过滤器名}}或v-bind:属性=“xxx| 过滤器名”
-
备注:
- 过滤器也可以接收额外参数、多个过滤器也可以串联
- 并没有改变原本的数据,是产生新的对应的数据
内置指令
我们学过的指令:
v-bind: 单向绑定解析表达式,可简写为: XXX
v-model: 双向数据绑定
v-for: 遍历数组/对象/字符串
v-on: 绑定事件监听,可简写为@
v-if: 条件渲染(动态控制节点是否存在)
v-else: 条件渲染(动态控制节点是否存在)
v-show: 条件渲染(动态控制节点是否展示)
v-text指令
-
作用: 向其所在的节点中渲染文本内容
-
与插值语法的区别: v-text会替换掉节点中的内容,{{xx}}则不会!
<div id="root">
<div>你好,{{name}}</div>
<div v-text="name"></div>
<!-- 替换掉这个div的内容 -->
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
name: '尚硅谷'
},
})
</script>
v-html指令
v-html指令:
- 作用: 向指定节点中渲染包含html结构的内容
- 与插值语法的区别:
- v-html会替换掉节点中所有的内容,{{xx}}则不会!
- v-html可以识别html结构
- 严重注意: v-html有安全性问题!!!
- 在网站上动态渲染任意HTML是非常危险的,容易导致XSS攻击
- 一定要在可信的内容上使用v-html,永不要在用户提交的内容上!
<!-- 准备好一个容器 -->
<div id="root">
<div>你好,{{name}}</div>
<div v-html="str"></div>
<div v-html="str2"></div>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
name: '尚硅谷',
str: '<h3>wtf</h3>',
str2: '<a href=javascript:location.href="http://www.baidu.com?"+document.cookie>点击999</a>'
},
})
</script>
v-cloak指令
<style>
[v-cloak]{
display: none;
}
</style>
</head>
<body>
<!-- 准备好一个容器 -->
<div id="root">
<h2 v-vloak>{{name}}</h2>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
name: '尚硅谷'
},
})
</script>
v-cloak指令(没有值):
- 本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-cloak属性。
- 使用css配合v-cloak可以解决网速慢时页面展示出{{xxx}}的问题
v-once指令
<!-- 准备好一个容器 -->
<div id="root">
<h2 v-once>初始化N值是:{{n}}</h2>
<h2 >当前N值是:{{n}}</h2>
<button @click="n++">点我n+1</button>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
n: 1
},
})
</script>
v-once指令:
- v-once所在节点在初次动态渲染后,就视为静态内容了。
- 以后数据的改变不会引起v-once所在结构的更新,可以用于优化性能。
v-pre指令
<div id="root">
<h2 v-pre>Vue其实很简单</h2>
<h2 v-pre>当前N值是:{{n}}</h2>
<button v-pre @click="n++">点我n+1</button>
</div>
v-pre指令:
- 跳过其所在节点的编译过程。
- 可利用它跳过:没有使用指令语法、没有使用插值语法的节点,会加快编译。
自定义指令_函数式
需求1:
- 定义一个v-big指令,和v-text功能相似。但会把绑定的数值放大10倍
<!-- 准备好一个容器 -->
<div id="root">
<h2>当前的n值是:<span v-text="n"></span></h2>
<h2>放大10倍后的n值是:<span v-big="n"></span></h2>
<button @click="n++">点我n+1</button>
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
n: 1
},
directives:{
// big函数何时会被调用?
// 指令与元素成功绑定时(一开始)
// 指令所在的模板被重新解析时。
big(element,binding){
//console.dir(a);
//console.log(a instanceof HTMLElement)
element.innerText = binding.value*10
}
}
})
</script>
需求2:
- 定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点
<!-- 准备好一个容器 -->
<div id="root">
<h2>当前的n值是:<span v-text="n"></span></h2>
<h2>放大10倍后的n值是:<span v-big="n"></span></h2>
<button @click="n++">点我n+1</button>
<hr/>
<input type="text" v-fbind:value="n" />
</div>
<script>
Vue.config.productionTip=false;
const vm = new Vue({
el:'#root',
data: {
n: 1
},
directives:{
// big函数何时会被调用?
// 指令与元素成功绑定时(一开始)
// 指令所在的模板被重新解析时。
big(element,binding){
//console.dir(a);
//console.log(a instanceof HTMLElement)
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;
//element.focus();
}
}
}
})
</script>
总结
双单词
v-big-number
'big-number'(element,binding){
}
注意:directives:{}里的方法的 this指向window
想要全局,跟过滤器差不多
Vue.directive('fbind',{
//指令与元素成功绑定时(一开始)
bind(element,binding){
element.value = binding.value;
},
//指令所在元素被插入页面时
inserted(element,binding){
element.focus();
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value;
//element.focus();
}
})
Vue.directive('big'function(element,binding){
//console.dir(a);
//console.log(a instanceof HTMLElement)
element.innerText = binding.value*10
})
自定义指令总结:
一、定义语法
- 局部指令:
new Vue({
directives:{指令名:配置对象}
})
或
new Vue({
directives(){}
})
- 全局指令:
Vue.directive(指令名,配置对象)
或
Vue.directive(指令名,回调函数)
二、配置对象中常用的3个回调
- bind:指令与元素成功绑定时调用
- inserted:指令所在元素被插入页面时调用
- update: 指令所在模板结构被重新解析时调用
三、备注
- 指令定义时不加v-,但使用时要加v-
- 指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名
生命周期
引出生命周期
<div id="root">
<h2 :style="{opacity}">欢迎学习Vue</h2>
</div>
<script>
Vue.config.productionTip=false;
new Vue({
el:'#root',
data: {
opacity: 1
},
methods: {
// change(){
// setInterval(() => {
// this.opacity-=0.01
// if(this.opacity <= 0)
// this.opacity = 1
// }, 16);
// }
},
//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>
生命周期:
- 又名: 生命周期回调函数、生命周期函数、生命周期钩子。
- 是什么: Vue在关键时刻帮我们调用的一些特殊名称的函数。
- 生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的
- 生命周期函数中的this指向是vm 或 组件实例对象。
创建流程
指的是创建: 数据监测、数据代理
挂载流程
debugger;
更新流程
<template></template>
不能作为根标签!
销毁流程
总结
vm生命周期:
- 将要创建 ===> 调用beforeCreate函数
- 创建完毕 ===> 调用created函数
- 将要挂载 ===> 调用beforeMount函数
- (重要)挂载完毕 ===> 调用mounted函数 ======重要的钩子
- 将要更新 ===> 调用beforeUpdate函数
- 更新完毕 ===> 调用updated函数
- (重要)将要销毁 ===> 调用beforeDestroy函数 ======重要的钩子
- 销毁完毕 ===> 调用destroyed函数
clearInterval(this.timer)
常用的生命周期钩子:
- mounted: 发生ajax请求、启动定时器、绑定自定义事件、订阅消息等[初始化操作]
- beforeDestroy: 清除定时器、解绑自定义事件、取消订阅消息等[收尾工作]
关于销毁Vue实例
- 销毁后借助Vue开发者工具看不到任何消息
- 销毁后自定义事件会失效,但原生DOM事件依然有效
- 一般不会在beforeDestroy操作数据,因为即使操作数据,也不会再触发更新流程了
Vue组件化编程
传统方式编写应用:
存在问题:
- 依赖关系混乱,不好维护
- 代码复用率不高
使用组件方式编写应用
组件的定义:
- 实现应用中局部功能
代码
和资源
的集合`
组件基本使用
Vue中使用组件的三大步骤:
- 定义组件(创建组件)
- 注册组件
- 使用组件(写组件标签)
一、如何定义一个组件?
使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但是区别如下:
- el不要写,为什么?
- 最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器
- data必须写成函数,为什么?
- 避免组件被复用时,数据存在引用关系。
备注: 使用template可以配置组件结构。
二、如何注册组件?
- 局部注册: 靠new Vue的时候传入components选项
- 全局注册:靠Vue.component(‘组件名’,组件)
三、编写组件标签:
<school></school>
<div id="root">
<hello></hello>
<h2>{{msg}}</h2>
<!-- 3、编写组件标签 -->
<school></school>
<hr>
<student></student>
<student></student>
</div>
<div id="root2">
<hello></hello>
</div>
<script>
Vue.config.productionTip=false;
//1、创建school组件 extend扩展 需要传入配置对象
const school = Vue.extend({
//组件定义时一定不要写el配置项,因为最终所有组件都要被一个vm管理,由vm决定服务于哪个容器
template: `
<div>
<h2 >学校名称:{{schoolName}}</h2>
<h2 >学校地址:{{address}}</h2>
<button @click="showName">点我提示学校名称</button>
</div>
`,
data(){
return {
schoolName: '尚硅谷',
address: '北京',
};
},
methods: {
showName(){
alert(this.schoolName);
}
}
})
//1、创建student组件
const student = Vue.extend({
template: `
<div>
<h2 >学生姓名:{{studentName}}</h2>
<h2 >学生年龄:{{age}}</h2>
</div>
`,
data(){
return {
studentName: '张三',
age: 18
}
}
})
//1、创建hello组件
const hello = Vue.extend({
template: `
<div>
你好!{{name}}
</div>
`,
data(){
return {
name: 'Tom'
}
}
})
//2、全局注册组件
Vue.component('hello',hello);
//创建vm
new Vue({
el:'#root',
data:{
msg: '你好'
},
//2、注册组件(局部注册)
components:{
school,
student
}
})
new Vue({
el:'#root2',
})
</script>
非单文件组件
一个文件中包含有N个组件
单文件组件
一个文件中只包含有1个组件a.vue
里面只允许一个组件
组件的几个注意点
几个注意点:
-
关于组件名:
- 一个单词组成:
- 第一种写法(首字母小写):school
- 第二种写法(首字母大写):School
- 多个单词组成:
- 第一种写法(kebab-case命名): my-school
- 第二种写法(CamelCase命名): MySchool(需要Vue脚手架支持)
- 备注:
- 组件名尽可能回避HTML中已有的元素名称,例如: h2、H2都不行
- 可以使用name配置项指定组件在开发者工具中呈现的名字。
- 一个单词组成:
-
关于组件标签:
- 第一种写法:
<school></school>
- 第二种写法:
<school/>
- 备注:不用使用脚手架时,
<school/>
会导致后续组件不能渲染。
- 第一种写法:
-
一个简写方式:
const school = Vue.extend(options)
可简写为:
const school = options
可以使用name配置项指定组件在开发者工具中呈现的名字
//1、创建hello组件
const hello = Vue.extend({
//可以使用name配置项指定组件在开发者工具中呈现的名字。
name: 'atguigu',
template: `
<div>
你好!{{name}}
</div>
`,
data(){
return {
name: 'Tom'
}
}
})
一个简写方式:
//1、创建hello组件
const hello = {
name: 'atguigu',
template: `
<div>
你好!{{name}}
</div>
`,
data(){
return {
name: 'Tom'
}
}
}
组件的嵌套
<div id="root">
</div>
<script>
Vue.config.productionTip=false;
//1、创建student组件 extend扩展 需要传入配置对象
const student = Vue.extend({
name: 'student',
//组件定义时一定不要写el配置项,因为最终所有组件都要被一个vm管理,由vm决定服务于哪个容器
template: `
<div>
<h2 >学生姓名:{{studentName}}</h2>
<h2 >学生年龄:{{age}}</h2>
<button @click="showName">点我提示</button>
</div>
`,
data(){
return {
studentName: 'cqz',
age: 23,
};
},
methods: {
showName(){
alert(this.studentName);
}
}
})
//1、创建school组件 extend扩展 需要传入配置对象
const school = Vue.extend({
name: 'school',
//组件定义时一定不要写el配置项,因为最终所有组件都要被一个vm管理,由vm决定服务于哪个容器
template: `
<div>
<h2 >学校名称:{{schoolName}}</h2>
<h2 >学校地址:{{address}}</h2>
<button @click="showName">点我提示学校名称</button>
<student></student>
</div>
`,
data(){
return {
schoolName: '尚硅谷',
address: '北京',
};
},
methods: {
showName(){
alert(this.schoolName);
}
},
components:{
student
}
})
const hello = Vue.extend({
template:`
<h1>{{msg}}</h1>
`,
data(){
return {
msg: '欢迎您'
}
}
})
const app = Vue.extend({
template: `
<div>
<hello></hello>
<school></school>
</div>
`,
components:{
school,
hello
}
})
//创建vm
new Vue({
template:`
<app></app>
`,
el:'#root',
//2、注册组件(局部注册)
components:{
app
}
})
</script>
VueComponent构造函数
关于VueComponent:
-
school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的
-
我们只需要写
<school/>
或<school></school>
,Vue解析时会帮我们创建school组件的实例对象,即Vue帮我们执行的: new VueComponent(options). -
特别注意: 每次调用Vue.extend,返回的都是一个全新的VueComponent!!!
-
关于this指向:
-
组件配置中:
- data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是[VueComponent实例对象]
-
new Vue()配置中:
- data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是[Vue实例对象]
-
-
VueComponent的实例对象,以后简称vc(也可称之为:组件实例对象)
Vue的实例对象,以后简称vm。
一个重要的内置关系
const d = new Demo();
函数构造函数才有Demo.prototype//显式原型对象
实例对象才有d.__proto__//隐式原型属性
实例的隐式原型属性,永远指向自己缔造者的原型对象
一个重要的内置关系:
VueComponentprototype.__proto__ === Vue.prototype
- 为什么要有这个关系:
- 让组件实例对象(vc)可以访问到Vue原型上的属性、方法
单文件组件
-
webpack
-
脚手架
四种写法:
school.vue
School.vue(一般选择)
my-school.vue
MySchool.vue(一般选择)
单文件组件
<template>
<!-- 组件的结构 -->
<div>
</div>
</template>
<script>
// 组件交互相关的代码(数据、方法等等)
</script>
<style>
/*
组件的样式
*/
</style>
外部想要使用需要暴露。
三种暴露方式:
第一种:分别暴露
export const school = Vue.extend({
})
第二种:统一暴露
export {school}
第三种: 默认暴露
export default school
一般只有一个的话使用默认暴露import ??? from ???
否则import {???} from ???
使用Vue脚手架
-
Vue脚手架是Vue官方提供的标准化开发工具(开发平台)
command
line
interface
具体步骤
全局安装@vue/cil
npm install -g @vue/cli
切换创建项目的目录,使用命令创建项目
选择Vue2
vue create xxx
启动项目
npm run serve
关闭项目
Ctrl+C
- 备注:
如出现下载缓慢配置淘宝镜像
npm config set registry https://registry.npm.taobao.org
Vue脚手架隐藏了所有webpack相关的配置,若想查看具体的webpack配置,执行:
vue inspect > output.js
cd Desktop
babel ES6===>ES5
eslint 语法检查
分析脚手架结构
.gitignore------git忽略文件配置
babel.config.js------babel配置文件
package.json-------包的说明书
package-lock.json------包版本控制文件
School.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2 >学校名称:{{schoolName}}</h2>
<h2 >学校地址:{{address}}</h2>
<button @click="showName">学校名称</button>
</div>
</template>
<script>
// 组件交互相关的代码(数据、方法等等)
export default {
name: 'School',
data(){
return {
schoolName: '尚硅谷',
address: '北京',
};
},
methods: {
showName(){
alert(this.schoolName);
}
}
}
</script>
<style>
/*
组件的样式
*/
.demo {
background-color: skyblue;
}
</style>
Student.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2 >学生姓名:{{name}}</h2>
<h2 >学生年龄:{{age}}</h2>
</div>
</template>
<script>
// 组件交互相关的代码(数据、方法等等)
export default {
name: 'Student',
data(){
return {
name: 'cqz',
age: '20',
};
}
}
</script>
<style>/*
组件的样式
*/
.demo {
background-color: skyblue;
}
</style>
App.vue
<template>
<div>
<img src="./assets/logo.png" alt="logo">
<school></school>
<student></student>
</div>
</template>
<script>
// 引入组件 .vue可以省略
import School from './components/School.vue'
import Student from './components/Student.vue'
export default {
name: 'App',
components:{
School,
Student
}
}
</script>
main.js
/*
该文件是整个项目的入口文件
*/
//引入Vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false
//创建Vue实例对象------vm
new Vue({
//完成功能:将App组件放入容器中
render: h => h(App),
}).$mount('#app')//el:'#app'
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- 针对IE浏览器的一个特殊配置,含义是让IE浏览器以最高的渲染级别渲染页面 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 开启移动端的理想视口 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 配置页签图标 -->
<link rel="icon" href="<%= BASE_URL%>favicon.ico">
<!-- 配置网页标题 -->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!-- 不支持js的浏览器打开,就渲染 <noscript>里的内容-->
<noscript>。。。。。。</noscript>
<!-- 容器 -->
<div id="app">
</div>
</body>
</html>
运行成功!!!
render函数
render: h=> h(App)
//render: q=>q('h1','你好')
/*
render(h){
return h('h1','你好');
}
*/
关于不同版本的Vue:
- vue.js与vue.runtime.xxx.js的区别:
- vue.js是完整版的Vue.包含:核心功能+模板解析器
- vue.runtime.xxx.js是运行版的Vue.只包含:核心功能:没有模板解析器
- 因为vue.runtime.xxx.js没有模板解析器,所以不能使用template配置项,需要使用render函数接收到的createElement函数去指定具体内容。
修改默认配置
vue inspect > output.js
查看Vue脚手架的默认配置
需要在package.json
同级目录下新建vue.config.js
官网查找并编写要修改的配置。没写的默认使用默认配置的
module.exports = {
pages: {
index: {
// page 的入口
entry: 'src/main.js',
},
},
lintOnSave: false
}
pages配置页面相关
lintOnSave配置自动检查相关
ref属性
原生js通过id
<h1 ref="title"></h1>
vue中通过ref属性获得this.$refs.title
此时的this是组件对象
<School ref="sch" />
此时this.$refs.title
获得的是School组件实例对象
ref属性
- 被用来给元素或子组件注册引用信息(id的替代者)
- 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
- 使用方式:
- 打标识:
<h1 ref="xxx">...</h1>
或<School ref="xxx></School>"
- 获取: this.$refs.xxx
- 打标识:
props配置
App.vue
<template>
<div>
<img src="./assets/logo.png" alt="logo">
<school></school>
<student name="cqz" :age="23"></student>
<!-- <student name="hh" :age="3"></student> -->
</div>
</template>
<script>
// 引入组件 .vue可以省略
import School from './components/School.vue'
import Student from './components/Student.vue'
export default {
name: 'App',
components:{
School,
Student
}
}
</script>
Student.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h1>{{msg}}</h1>
<h2 >学生姓名:{{name}}</h2>
<h2 >学生年龄:{{myAge}}</h2>
<button @click="updateAge">年龄++</button>
</div>
</template>
<script>
// 组件交互相关的代码(数据、方法等等)
export default {
name: 'Student',
data(){
return {
msg: "欢迎您",
myAge: this.age
};
},
methods:{
updateAge(){
this.myAge++;
}
},
props:['name','age'] //简单声明接收
//接收的同时对数据进行类型限制
// props:{
// name:String,
// age: Number
// },
//完整写法
//接收的同时对数据进行类型限制+默认值的指定+必要性
/*
props:{
name:{
type: String,//name字符串
required: true //name是必须传的
},
age:{
type:Number,
default: 99//默认值
}
}
*/
}
</script>
<style>/*
组件的样式
*/
.demo {
background-color: skyblue;
}
</style>
配置项props
功能: 让组件接收外部传过来的数据
-
传递数据:
<Demo name="xxx" />
-
接收数据:
-
第一种方式(只接收):
props:['name']
-
第二种方式(限制类型):
props:{ name: String }
-
第三种方式(限制类型、限制必要性、指定默认值):
props:{ name:{ type: String,//name字符串 required: true //name是必须传的 }, age:{ type:Number, default: 99//默认值 } }
-
备注:
props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。
mixin混入(合)
将共用的配置编写进src目录下js文件
mixin.js
export const mixin = {
methods:{
showName(){
alert(this.name);
}
},
}
在组件中引入文件并使用
Student.vue
import {mixin} from '../mixin'
mixins: [mixin]
<template>
<!-- 组件的结构 -->
<div class="demo">
<h1>{{msg}}</h1>
<h2 @click="showName">学生姓名:{{name}}</h2>
<h2 >学生年龄:{{age}}</h2>
</div>
</template>
<script>
import {mixin} from '../mixin'
// 组件交互相关的代码(数据、方法等等)
export default {
name: 'Student',
data(){
return {
msg: "欢迎您",
name: "小丑",
age: 12
};
},
mixins: [mixin]
}
</script>
<style>/*
组件的样式
*/
.demo {
background-color: skyblue;
}
</style>
全局混入
将共用的配置编写进src目录下js文件后,
在main.js下引入
import {mixin} from './mixin'
Vue.mixin(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 = xxx
}
使用插件: Vue.use(...)
scoped样式
使用lang属性,需要安装less-loader
<style lang="less">
</style>
npm i less-loader
npm view webpack versions
less-loader 8 及 以上都是为webpack5服务的
vue脚手架使用的是webpack4 所以建议安装less-loader 7
npm i less-loader@7
scoped样式
作用: 让样式在局部生效,防止冲突。
写法:
<style scoped>
</style>
可以添加lang="css"
或lang="less"
浏览器本地存储
//设置
localStorage.setItem('msg','hello')
localStorage.setItem('msg',666)
localStorage.setItem('msg',JSON.stringify(obj))
JSON.parse(xxx)//JSON.parse(null)===null
//获取
localStorage.getItem('msg')
//移除
localStorage.removeItem('msg')
//清空
localStorage.clear()
参数全部转为字符串
sessionStorage
//设置
sessionStorage.setItem('msg','hello')
sessionStorage.setItem('msg',666)
sessionStorage.setItem('msg',JSON.stringify(obj))
JSON.parse(xxx)//JSON.parse(null)===null
//获取
sessionStorage.getItem('msg')
//移除
sessionStorage.removeItem('msg')
//清空
sessionStorage.clear()
WebStorage
- 存储内容大小一般支持5MB左右(不同浏览器可能还不一样)
- 浏览器端通过Window.sessionStorage和Window.localStorage属性来实现本地存储机制
- 相关API
- xxxStorage.setItem(‘key’,‘value’);
- 该方法接收一个键值对作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值
- xxxStorage.getItem(‘key’’);
- 该方法接收一个键名作为参数,返回键名对应的值
- xxxStorage.removeItem(‘key’);
- 该方法接收一个键名作为参数,并把该键名从存储中删除
- xxxStorage.clear()
- 该方法会清空存储中的所有数据
- xxxStorage.setItem(‘key’,‘value’);
- 备注:
- SessionStorage存储的内容会随着浏览器窗口关闭而消失
- localStorage存储的内容,需要手动清除才会消失
xxxStorage.getItem('key'');
如果key对应的value获取不到,那么getItem的返回值是nullJSON.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')
-
组件上也可以绑定原生DOM事件,需要使用
native
修饰符 -
注意:通过
this.$refs.xxx.$on('atguigu',回调)
绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!!!
App.vue
<template>
<div class="app">
<h1>{{msg}}</h1>
<img src="./assets/logo.png" alt="logo">
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
<school :getSchoolName="getSchoolName"></school>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法:使用@或v-on) -->
<!-- <student v-on:atguigu="getStudentName" ></student> -->
<!-- <student @atguigu="getStudentName" ></student> -->
<!-- <student name="hh" :age="3"></student> -->
<Student ref="student" />
</div>
</template>
<script>
// 引入组件 .vue可以省略
import School from './components/School.vue'
import Student from './components/Student.vue'
export default {
name: 'App',
components:{
School,
Student
},
data(){
return {
msg: '你好!'
};
},
methods:{
getSchoolName(name){
console.log("App收到名字:",name)
},
getStudentName(name){
// getStudentName(name,...params){
console.log('demo被调用了!',name);
}
},
mounted(){
setTimeout(()=>{
// this.$refs.student.$on('atguigu',this.getStudentName);//绑定自定义事件!
// this.$refs.student.$once('atguigu',this.getStudentName);//只执行一次
},3000)
}
}
</script>
<style scoped>
.app {
background-color: gray;
}
</style>
School.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2 >学校名称:{{name}}</h2>
<h2 >学校地址:{{address}}</h2>
<button @click="showName">学校名称</button>
<button @click="sendSchoolName">传给App</button>
</div>
</template>
<script>
//import {mixin} from '../mixin'
// 组件交互相关的代码(数据、方法等等)
export default {
name: 'School',
props:['getSchoolName'],
data(){
return {
name: '尚硅谷',
address: '北京',
};
},
// mixins: [mixin]
methods:{
sendSchoolName(){
this.getSchoolName(this.name);
}
}
}
</script>
<style scoped>
/*
组件的样式
*/
.demo {
background-color: orange;
}
</style>
Student.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h1>{{msg}}</h1>
<h2 @click="showName">学生姓名:{{name}}</h2>
<h2 >学生年龄:{{age}}</h2>
<button @click="sendStudentName">2传给App</button>
</div>
</template>
<script>
//import {mixin} from '../mixin'
// 组件交互相关的代码(数据、方法等等)
export default {
name: 'Student',
data(){
return {
msg: "欢迎您",
name: "小丑",
age: 12
};
},
// mixins: [mixin]
methods:{
sendStudentName(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name);
//后面还可以传数据、对象等等
}
}
}
</script>
<style scoped>/*
组件的样式
*/
.demo {
background-color: skyblue;
}
</style>
全局事件总线(组件之间通信)
全局事件总线:任意组件通信
全局事件总线(GlobalEventBus)
-
一种组件间通信的方式,适用于任意组件间通信
-
安装全局事件总线
new Vue({ el: '#app', render: h=> h(App), beforeCreate(){ Vue.prototype.$bus = this;//安装全局事件总线 }//$bus总线 })
-
使用事件总线:
-
接收数据: A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回溯留在A组件自身
methods(){ demo(data){......} } mounted() { //console.log('School',this); this.$bus.$on('hello',(data)=>{ console.log('School收到',data) }) }, beforeDestroy(){ this.$bus.$off('hello'); }
-
提供数据:
this.$bus.$emit('xxx',数据)
-
-
最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。
Student.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h1>{{msg}}</h1>
<h2 >学生姓名:{{name}}</h2>
<h2 >学生年龄:{{age}}</h2>
<button @click="sendStudentName">把学生名给School组件</button>
</div>
</template>
<script>
export default {
name: 'Student',
data(){
return {
msg: "欢迎您",
name: "小丑",
age: 12
};
},
methods:{
sendStudentName(){
this.$bus.$emit('hello',this.name)
}
}
}
</script>
School.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2 >学校名称:{{name}}</h2>
<h2 >学校地址:{{address}}</h2>
</div>
</template>
<script>
//import {mixin} from '../mixin'
// 组件交互相关的代码(数据、方法等等)
export default {
name: 'School',
data(){
return {
name: '尚硅谷',
address: '北京',
};
},
mounted() {
//console.log('School',this);
this.$bus.$on('hello',(data)=>{
console.log('School收到',data)
})
},
beforeDestroy(){
this.$bus.$off('hello');
}
}
</script>
<style scoped>
/*
组件的样式
*/
.demo {
background-color: orange;
}
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
// const demo = Vue.extend({})
// const d = new demo();
// Vue.prototype.x = d;
new Vue({
el: '#app',
render: h=> h(App),
beforeCreate(){
Vue.prototype.$bus = this;//安装全局事件总线
}//$bus总线
})
消息订阅与发布_pubsub
消息订阅与发布:
- 订阅消息: 消息名
- 发布消息: 消息内容
pubsub-js
publish-subscribe
npm i pubsub-js
-
一种组件间通信的方式,适用于任意组件间通信
-
使用步骤:
- 安装pubsub:
npm i pubsub-js
- 引入:
import pubsub from 'pubsub-js'
- 接收数据: A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
methods(){ demo(data){...} } mounted() { this.pubID = pubsub.subscribe('hello',function(msgName,data){ console.log('hello执行成功!',msgName,data); // pubsub.subscribe('hello',function(msgName,data)=>{} //注意this }) },
- 安装pubsub:
-
提供数据:
pubsub.publish('xxx',数据);
-
最好在beforeDestroy钩子中,用
pubsub.unsubscribe(this.pubID)
去取消订阅
Student.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h1>{{msg}}</h1>
<h2 >学生姓名:{{name}}</h2>
<h2 >学生年龄:{{age}}</h2>
<button @click="sendStudentName">把学生名给School组件</button>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: 'Student',
data(){
return {
msg: "欢迎您",
name: "小丑",
age: 12
};
},
methods:{
sendStudentName(){
pubsub.publish('hello',666);
}
}
}
</script>
<style scoped>/*
组件的样式
*/
.demo {
background-color: skyblue;
}
</style>
School.vue
<template>
<!-- 组件的结构 -->
<div class="demo">
<h2 >学校名称:{{name}}</h2>
<h2 >学校地址:{{address}}</h2>
</div>
</template>
<script>
import pubsub from 'pubsub-js'
export default {
name: 'School',
data(){
return {
name: '尚硅谷',
address: '北京',
};
},
mounted() {
this.pubID = pubsub.subscribe('hello',function(msgName,data){
console.log('hello执行成功!',msgName,data);
// pubsub.subscribe('hello',function(msgName,data)=>{}
//注意this
})
},
beforeDestroy(){
pubsub.unsubscribe(this.pubID)
}
}
</script>
<style scoped>
/*
组件的样式
*/
.demo {
background-color: orange;
}
</style>
全局事件总线更好!pubsub不常用!
$nextTick
this.$nextTick(function(){
this.$refs.inputTitle.focus();
})
$nextTick
下一轮的意思
$nextTick
语法: this.$nextTick(回调函数)
作用: 在下一次DOM更新结束后执行其指定的回调
什么时候用: 当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。
动画效果
Test.vue
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition appear>
<!-- :appear="true" -->
<h1 v-show="isShow">你好!</h1>
</transition>
</div>
</template>
<script>
export default {
name: 'Test',
data(){
return {
isShow: true
};
}
}
</script>
<style lang="css" scoped>
h1 {
background-color: greenyellow;
}
.v-enter-active {
/*
<transition name="hello"></transition>
hello-enter-active
*/
animation: atguigu 0.5s; /* linear; */
}
.v-leave-active {
/* v-leave-active */
animation: atguigu 0.5s reverse;
}
@keyframes atguigu {/* identifier */
from{
transform: translateX(-100%);
}
to{
transform: translateX(0px);
}
}
</style>
过渡效果
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition name="hello" appear>
<!-- :appear="true" -->
<h1 v-show="isShow">你好!</h1>
</transition>
</div>
</template>
<script>
export default {
name: 'Test',
data(){
return {
isShow: true
};
}
}
</script>
<style lang="css" scoped>
h1 {
background-color: orange;
}
/* 进入的起点 离开的终点 */
.hello-enter, .hello-leave-to {
transform: translateX(-100%);
}
/* 进入的终点 离开的起点*/
.hello-enter-to,.hello-leave {
transform: translateX(0);
}
.hello-enter-active,.hello-leave-active{
transition: 0.5s linear;
}
</style>
多个元素过渡
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition-group name="hello" appear>
<!-- :appear="true" -->
<h1 v-show="isShow" key="1"> 你好!</h1>
<h1 v-show="isShow" key="2">你好!</h1>
</transition-group>
</div>
</template>
集成第三方
安装
npm install animate.css
引用
import 'animate.css'
Test3.vue
<template>
<div>
<button @click="isShow = !isShow">显示/隐藏</button>
<transition-group name="animate__animated animate__bounce"
appear
enter-active-class="animate__tada"
leave-active-class="animate__backOutUp"
>
<!-- :appear="true" -->
<h1 v-show="!isShow" key="1"> 你好!</h1>
<h1 v-show="isShow" key="2">你好!</h1>
</transition-group>
</div>
</template>
<script>
import 'animate.css'
export default {
name: 'Test3',
data(){
return {
isShow: true
};
}
}
</script>
<style lang="css" scoped>
h1 {
background-color: orange;
}
</style>
Vue封装的过渡与动画
作用: 在插入、更新或移除DOM元素时,在合适的时候给元素添加样式类名。
写法:
-
准备好样式:
- v-enter: 进入的起点
- v-enter-active:进入过程中
- v-enter-to:进入的终点
-
元素离开的样式:
- v-leave:离开的起点
- v-leave-active:离开的过程中
- v-leave-to: 离开的终点
-
使用
<transition>
包裹要过渡的元素,并配置name属性:<transition name="hello" appear> <!-- :appear="true" --> <h1 v-show="isShow">你好!</h1> </transition>
-
备注
若有多个元素需要过渡,则需要使用:
<transition-group>
,且每个元素都要指定key
值
Vue中的ajax
配置代理_方式一
xhr new XMLHttpRequest();
xhr.open();
xhr.send();
jQuery
$.get
$.post
axios
fetch
vue-resource
下载并引入axios
npm i axios
解决跨域:
1 cors
2 jsonp
只能解决get
3 配置代理服务器
两台服务器之间用http请求
1、nginx
2、vue-cli
第一步: 配置文件中
vue.config.js
// 开启代理服务器 地址是实际要请求的地址和端口号
devServer: {
proxy: 'http://localhost:5000'
}
App.vue
<template>
<div class="app">
<button @click="getStudents">获取学生信息</button>
</div>
</template>
<script>
import axios from 'axios'
export default{
name: 'App',
methods: {
getStudents(){
axios.get('http://localhost:8080/students').then(
response => {
console.log('请求成功!',response.data);
},
error => {
console.log('请求失败!',error.message);
}
)
}
}
}
</script>
不能配置多个,且如果本地有要请求的同名文件等就不会请求服务器
配置代理_方式二
vue.config.js
module.exports = {
pages: {
index: {
// page 的入口
entry: 'src/main.js',
},
},
lintOnSave: false,
// 开启代理服务器(方式1)
// devServer: {
// proxy: 'http://localhost:5000'
// }
// 开启代理服务器(方式2)
devServer: {
proxy: {
'/atguigu': {//请求前缀
target: 'http://localhost:5000',
pathRewrite:{'^/atguigu':''},
//ws: true,//用于支持websocket
//changeOrigin: true//默认为true 用于控制请求头中的host值
},
'/demo': {//请求前缀
target: 'http://localhost:5001',
pathRewrite:{'^/demo':''},
//ws: true,//用于支持websocket
//changeOrigin: true//默认为true 用于控制请求头中的host值
},
// '/foo': {
// target: ''
// }
}
}
}
App.vue
<template>
<div class="app">
<button @click="getStudents">获取学生信息</button>
<button @click="getCars">获取汽车信息</button>
</div>
</template>
<script>
import axios from 'axios'
export default{
name: 'App',
methods: {
getStudents(){
axios.get('http://localhost:8080/atguigu/students').then(
response => {
console.log('请求成功!',response.data);
},
error => {
console.log('请求失败!',error.message);
}
)
},
getCars(){
axios.get('http://localhost:8080/demo/cars').then(
response => {
console.log('请求成功!',response.data);
},
error => {
console.log('请求失败!',error.message);
}
)
}
}
}
</script>
总结:
- 方式一:
在vue.config,js中添加如下配置:
devServer: {
proxy: 'http://localhost:5000'
}
说明:
优点:配置简单,请求资源时直接发送(8080)即可
缺点:不能配置多个代理,不能灵活的控制请求是否走代理
工作方式: 若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器(优先匹配前端资源)
- 方式二:
编写vue.config,js配置具体代理规则:
module.exports = {
pages: {
index: {
// page 的入口
entry: 'src/main.js',
},
},
lintOnSave: false,
// 开启代理服务器(方式1)
// devServer: {
// proxy: 'http://localhost:5000'
// }
// 开启代理服务器(方式2)
devServer: {
proxy: {
'/atguigu': {//请求前缀
target: 'http://localhost:5000',
pathRewrite:{'^/atguigu':''},
//ws: true,//用于支持websocket
//changeOrigin: true//默认为true 用于控制请求头中的host值
},
'/demo': {//请求前缀
target: 'http://localhost:5001',
pathRewrite:{'^/demo':''},
//ws: true,//用于支持websocket
//changeOrigin: true//默认为true 用于控制请求头中的host值
},
// '/foo': {
// target: ''
// }
}
}
}
说明:
优点: 可以配置多个代理,且可以灵活的控制请求是否走代理
缺点: 配置略微繁琐,请求资源时必须加前缀
vue-resource
封装了xhr
1、安装
npm i vue-resource
this.$http.get('http://localhost:8080/atguigu/students').then(
response => {
console.log('请求成功!',response.data);
},
error => {
console.log('请求失败!',error.message);
}
)
与axios用法差不多,但官方已经不维护,交给其它团队!
vue1.0使用较多。
axios更为优秀!
插槽
Category – 分类
- 不使用插槽:
Category.vue
<template>
<div class="category">
<h3>{{title}}分类</h3>
<ul>
<li v-for="(item,index) in listData" :key="index" >{{item}}</li>
</ul>
</div>
</template>
<script>
export default {
name: 'Category',
props:['listData','title']
}
</script>
<style scoped>
.category {
background-color: skyblue;
width: 200px;
height: 300px;
}
h3{
text-align: center;
background-color: orange;
}
</style>
App.vue
<template>
<div class="container">
<Category title="美食" :listData="foods"/>
<Category title="游戏" :listData="games"/>
<Category title="电影" :listData="films"/>
</div>
</template>
<script>
import Category from './components/Category'
export default{
name: 'App',
components:{Category},
data(){
return {
foods:['火锅','烧烤','小龙虾','牛排'],
games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
films:['《教父》','《拆弹专家》','《你好,李焕英》']
}
}
}
</script>
<style scoped>
.container{
display: flex;
justify-content: space-around;
}
</style>
默认插槽
Category.vue
<template>
<div class="category">
<h3>{{title}}分类</h3>
<!-- 定义一个插槽(等着组件的使用者进行填充) -->
<slot>可以设置默认值,使用者没有传递具体结构时出现</slot>
</div>
</template>
<script>
export default {
name: 'Category',
props:['title']
}
</script>
<style scoped>
.category {
background-color: skyblue;
width: 200px;
height: 300px;
}
h3 {
text-align: center;
background-color: orange;
}
</style>
App.vue
<template>
<div class="container">
<Category title="美食">
<img src="https://img2.baidu.com/it/u=1320386730,3153153183&fm=26&fmt=auto&gp=0.jpg"/>
</Category>
<Category title="游戏" >
<ul>
<li v-for="(item,index) in games" :key="index" >{{item}}</li>
</ul>
</Category>
<Category title="电影">
<video controls src="https://chuangyixinmei.oss-cn-beijing.aliyuncs.com/2020/05/28/159064648384.mp4"></video>
</Category>
</div>
</template>
<script>
import Category from './components/Category'
export default{
name: 'App',
components:{Category},
data(){
return {
foods:['火锅','烧烤','小龙虾','牛排'],
games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
films:['《教父》','《拆弹专家》','《你好,李焕英》']
}
}
}
</script>
<style scoped>
.container{
display: flex;
justify-content: space-around;
}
video {
width: 100%;
}
img {
width: 100%;
}
</style>
具名插槽
Category.vue
<template>
<div class="category">
<h3>{{title}}分类</h3>
<!-- 定义一个插槽(等着组件的使用者进行填充) -->
<slot name="center"></slot>
<slot name="footer"></slot>
</div>
</template>
<script>
export default {
name: 'Category',
props:['title']
}
</script>
<style scoped>
.category {
background-color: skyblue;
width: 200px;
height: 300px;
}
h3 {
text-align: center;
background-color: orange;
}
</style>
App.vue
<template>
<div class="container">
<Category title="美食">
<img slot="center" src="https://img2.baidu.com/it/u=1320386730,3153153183&fm=26&fmt=auto&gp=0.jpg"/>
<a slot="footer" href="#">更多美食</a>
</Category>
<Category title="游戏" >
<ul slot="center">
<li v-for="(item,index) in games" :key="index" >{{item}}</li>
</ul>
<div class="foot" slot="footer" >
<a href="#">单机游戏</a>
<a href="#">网页游戏</a>
</div>
</Category>
<Category title="电影">
<video slot="center" controls src="https://chuangyixinmei.oss-cn-beijing.aliyuncs.com/2020/05/28/159064648384.mp4"></video>
<template v-slot:footer>
<!-- slot="footer" -->
<!-- v-slot:footer 只能用于<template></template>标签 -->
<div class="foot">
<a href="#">经典</a>
<a href="#">热门</a>
<a href="#">推荐</a>
</div>
<h4 >欢迎前来观影</h4>
</template>
</Category>
</div>
</template>
<script>
import Category from './components/Category'
export default{
name: 'App',
components:{Category},
data(){
return {
foods:['火锅','烧烤','小龙虾','牛排'],
games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
films:['《教父》','《拆弹专家》','《你好,李焕英》']
}
}
}
</script>
<style scoped>
.container,.foot{
display: flex;
justify-content: space-around;
}
video {
width: 100%;
}
img {
width: 100%;
}
h4 {
text-align: center;
}
</style>
作用域插槽
Category.vue
<template>
<div class="category">
<h3>{{title}}分类</h3>
<slot :games="games"></slot>
</div>
</template>
<script>
export default {
name: 'Category',
props:['title'],
data(){
return {
games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
}
}
}
</script>
<style scoped>
.category {
background-color: skyblue;
width: 200px;
height: 300px;
}
h3 {
text-align: center;
background-color: orange;
}
</style>
App.vue
<template>
<div class="container">
<Category title="游戏" >
<template scope="test1">
<ul>
<li v-for="(item,index) in test1.games" :key="index" >{{item}}</li>
</ul>
</template>
</Category>
<Category title="游戏" >
<template scope="{games}">
<ol>
<li v-for="(item,index) in games" :key="index" >{{item}}</li>
</ol>
</template>
</Category>
<Category title="游戏" >
<template slot-scope="{games}">
<h4 v-for="(item,index) in games" :key="index" >{{item}}</h4>
</template>
</Category>
</div>
</template>
<script>
import Category from './components/Category'
export default{
name: 'App',
components:{Category},
}
</script>
<style scoped>
.container,.foot{
display: flex;
justify-content: space-around;
}
video {
width: 100%;
}
img {
width: 100%;
}
h4 {
text-align: center;
}
</style>
作用:
让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父组件===>子组件
分类:
默认插槽、具名插槽、作用域插槽
使用方式:
- 默认插槽
- 具名插槽
- 作用域插槽
作用域插槽:
理解: 数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)
vuex
什么是vuex?
专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。
解决多组件共享数据
什么时候使用Vuex
- 多个组件依赖于同一状态
- 来自不同组件的行为需要变更同一状态
纯vue求和案例
Count.vue
<template>
<div>
<h1>当前求和为: {{sum}}</h1>
<select v-model.number="n">
<option value="1">1</option>
<!-- :value="1" 或者 v-model.number="n"-->
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>
<script>
export default {
name:'Count',
data(){
return {
sum:0,
n:1 //用户选择的数据
}
},
methods: {
increment(){
this.sum += this.n;
},
decrement(){
this.sum -= this.n;
},
incrementOdd(){
if(this.sum % 2){
this.sum += this.n
}
},
incrementWait(){
setTimeout(()=>{
this.sum += this.n;
},500)
}
}
}
</script>
<style scoped>
button{
margin-left: 5px;
}
</style>
App.vue
<template>
<div>
<Count></Count>
</div>
</template>
<script>
import Count from './components/Count'
export default{
name: 'App',
components:{Count},
}
</script>
<style scoped>
</style>
搭建Vuex环境
安装npm i vuex
main.js
import Vuex from 'vuex'
Vue.use(Vuex);
src文件夹下建立store
文件夹,里面写index.js
index.js
//该文件用于创建Vuex中最为核心额store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
Vue.use(Vuex);
//准备actions--用于响应组件中的动作
const actions = {}
//准备mutations--用于操作数据(state)
const mutations = {}
//准备state--用于存储数据
const state = {}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state
})
main.js
import Vue from 'vue'
import App from './App.vue'
import vueResource from 'vue-resource'
import store from './store'//默认引入/index
Vue.config.productionTip = false
//使用插件
Vue.use(vueResource);
// const demo = Vue.extend({})
// const d = new demo();
// Vue.prototype.x = d;
new Vue({
el: '#app',
render: h=> h(App),
store
})
import store from './store'//默认引入/index
要在Vue.use(Vuex);
之后执行,但是js文件中统一先执行import
语句,所以我们在index.js
中写Vue.use(Vuex);
vuex求和案例
vuex的基本使用:
Count.vue
<template>
<div>
<h1>当前求和为: {{$store.state.sum}}</h1>
<select v-model.number="n">
<option value="1">1</option>
<!-- :value="1" 或者 v-model.number="n"-->
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>
<script>
export default {
name:'Count',
data(){
return {
n:1 //用户选择的数据
}
},
methods: {
increment(){
this.$store.commit('ADD',this.n);
},
decrement(){
this.$store.commit('CUT',this.n);
},
incrementOdd(){
this.$store.dispatch('addOdd',this.n);
},
incrementWait(){
this.$store.dispatch('addWait',this.n);
}
}
}
</script>
<style scoped>
button{
margin-left: 5px;
}
</style>
index.js
//该文件用于创建Vuex中最为核心的store
import { setTimeout } from 'core-js';
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
Vue.use(Vuex);
//准备actions--用于响应组件中的动作
const actions = {
addOdd(context,value){
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
setTimeout(()=>{
context.commit('ADD',value)
},500)
}
}
//准备mutations--用于操作数据(state)
const mutations = {
ADD(state,value){
state.sum+=value;
},
CUT(state,value){
state.sum-=value;
}
}
//准备state--用于存储数据
const state = {
sum:0,
}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state
})
vuex开发者工具的使用
使用vue插件
组件中读取vuex中的数据: $store.state.sum
组件中修改vuex中的数据:$store.dispatch('actions中的方法名',数据)
或$store.commit('mutations中的方法名',数据)
备注: 若没有网络请求或其它业务逻辑,组件中也可越过actions,即不写dispatch
,直接编写commit
getters配置项
1 概念: 当state中的数据需要经过加工后再使用时,可以使用getters加工。
2 在store.js
中追加getters
配置
//准备getters---用于将state中的数据进行加工
const getters = {
bigSum(state){
return state.sum*10
}
}
//创建并暴露store,记得暴露getters
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
3 在组件中读取数据:$store.getters.bigSum
mapState与mapGetter
需要先在vue组件中引入import {mapState,mapGetters} from 'vuex'
mapState
用于帮助我们映射state
中的数据为计算属性
computed:{
//靠程序员自己亲自去写计算属性
// he(){
// return yhis.$store.state.sum
// }
//借助mapState生成计算属性,从state中读取数据。(对象写法)
// ...mapState({
// he:'sum',
// xuexiao:'school',
// xuexi:'subject'
// }),
//借助mapState生成计算属性,从state中读取数据。(数组写法)
...mapState(['sum','school','subject']),
}
mapGetters
用于帮助我们映射Getters
中的数据为计算属性
computed:{
// bigSum(){
// return this.$store.getters.bigSum
// },
//借助mapGetters生成计算属性,从Getters中读取数据。(对象写法)
...mapGetters({bigSum:'bigSum'}),
//借助mapGetters生成计算属性,从Getters中读取数据。(数组写法)
...mapGetters(['bigSum'])
}
mapActions与mapMutations
需要先在vue组件中引入import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
mapActions
方法,用于帮助我们生成与actions
对话的方法,即:包含$store.dispatch(xxx)
的函数
methods: {
/************************* */
//程序员亲自写方法
// incrementOdd(){
// this.$store.dispatch('addOdd',this.n);
// },
// incrementWait(){
// this.$store.dispatch('addWait',this.n);
// },
//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法,数组写法略)
...mapActions({incrementOdd:'addOdd',incrementWait:'addWait'})
},
mapMutations
方法:用于帮助我们生成mutations
对话的方法,即:包含$store.commit(xxx)
的函数
methods: {
//程序员亲自写方法
// increment(){
// this.$store.commit('ADD',this.n);
// },
// decrement(){
// this.$store.commit('CUT',this.n);
// },
//借助mapMutations生成对应的方法,方法中会调用commit去联系mutation(对象写法,数组写法略)
...mapMutations({increment:'ADD',decrement:'CUT'}),
},
备注: mapActions与mapMutations
使用时,若需要传递参数需要,在模板中绑定事件时传递好参数,否则参数是事件对象。
Count.vue
<template>
<div>
<h1>当前求和为: {{sum}}</h1>
<h3>当前求和放大10倍为:{{bigSum}}</h3>
<h3>我在{{school}},学习{{subject}}</h3>
<select v-model.number="n">
<option value="1">1</option>
<!-- :value="1" 或者 v-model.number="n"-->
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)">当前求和为奇数再加</button>
<button @click="incrementWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data(){
return {
n:1 //用户选择的数据
}
},
computed:{
//借助mapState生成计算属性,从state中读取数据。(对象写法)
// ...mapState({
// he:'sum',
// xuexiao:'school',
// xuexi:'subject'
// }),
//借助mapState生成计算属性,从state中读取数据。(数组写法)
...mapState(['sum','school','subject']),
...mapGetters({bigSum:'bigSum'}),
//借助mapGetters生成计算属性,从Getters中读取数据。(数组写法)
...mapGetters(['bigSum'])
},
methods: {
//程序员亲自写方法
// increment(){
// this.$store.commit('ADD',this.n);
// },
// decrement(){
// this.$store.commit('CUT',this.n);
// },
//借助mapMutations生成对应的方法,方法中会调用commit去联系mutation(对象写法,数组写法略)
...mapMutations({increment:'ADD',decrement:'CUT'}),
/************************* */
//程序员亲自写方法
// incrementOdd(){
// this.$store.dispatch('addOdd',this.n);
// },
// incrementWait(){
// this.$store.dispatch('addWait',this.n);
// },
//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法,数组写法略)
...mapActions({incrementOdd:'addOdd',incrementWait:'addWait'})
},
mounted(){
}
}
</script>
<style scoped>
button{
margin-left: 5px;
}
</style>
多组件共享数据
Person.vue
<template>
<div>
<input type="text" placeholder="请输入名字:" v-model="name"/>
<button @click="add">添加</button>
<ul>
<li v-for="p in personList" :key="p.id">{{p.name}}</li>
</ul>
<h3 style="color:red">Count组件总和:{{sum}}</h3>
</div>
</template>
<script>
import {mapState} from 'vuex'
import {nanoid} from 'nanoid'
export default {
name:'Person',
data(){
return {
name:''
}
},
computed:{
// personList(){
// return this.$store.state.personList
// }
...mapState(['personList','sum'])
},
methods:{
add(){
const personObj = {id: nanoid(),name:this.name}
this.$store.commit('ADD_PERSON',personObj)
this.name=''
}
}
}
</script>
<style scoped>
</style>
Count.vue
<template>
<div>
<h1>当前求和为: {{sum}}</h1>
<h3>当前求和放大10倍为:{{bigSum}}</h3>
<h3>我在{{school}},学习{{subject}}</h3>
<h3 style="color:red">Person组件总人数:{{personList.length}}</h3>
<select v-model.number="n">
<option value="1">1</option>
<!-- :value="1" 或者 v-model.number="n"-->
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)">当前求和为奇数再加</button>
<button @click="incrementWait(n)">等一等再加</button>
</div>
</template>
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
name:'Count',
data(){
return {
n:1 //用户选择的数据
}
},
computed:{
//借助mapState生成计算属性,从state中读取数据。(对象写法)
// ...mapState({
// he:'sum',
// xuexiao:'school',
// xuexi:'subject'
// }),
//借助mapState生成计算属性,从state中读取数据。(数组写法)
...mapState(['sum','school','subject','personList']),
...mapGetters({bigSum:'bigSum'}),
//借助mapGetters生成计算属性,从Getters中读取数据。(数组写法)
...mapGetters(['bigSum'])
},
methods: {
//程序员亲自写方法
// increment(){
// this.$store.commit('ADD',this.n);
// },
// decrement(){
// this.$store.commit('CUT',this.n);
// },
//借助mapMutations生成对应的方法,方法中会调用commit去联系mutation(对象写法,数组写法略)
...mapMutations({increment:'ADD',decrement:'CUT'}),
/************************* */
//程序员亲自写方法
// incrementOdd(){
// this.$store.dispatch('addOdd',this.n);
// },
// incrementWait(){
// this.$store.dispatch('addWait',this.n);
// },
//借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法,数组写法略)
...mapActions({incrementOdd:'addOdd',incrementWait:'addWait'})
},
mounted(){
}
}
</script>
<style scoped>
button{
margin-left: 5px;
}
</style>
index.js
//该文件用于创建Vuex中最为核心额store
import { setTimeout } from 'core-js';
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
Vue.use(Vuex);
//准备actions--用于响应组件中的动作
const actions = {
addOdd(context,value){
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
setTimeout(()=>{
context.commit('ADD',value)
},500)
}
}
//准备mutations--用于操作数据(state)
const mutations = {
ADD(state,value){
state.sum+=value;
},
CUT(state,value){
state.sum-=value;
},
ADD_PERSON(state,value){
state.personList.unshift(value)
}
}
//准备state--用于存储数据
const state = {
sum:0,
school: '理工',
subject:'Vue',
personList:[
{id:'001',name:'张三'},
]
}
//准备getters---用于将state中的数据进行加工
const getters = {
bigSum(state){
return state.sum*10
}
}
//创建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
App.vue
<template>
<div>
<Count></Count>
<hr/>
<Person/>
</div>
</template>
<script>
import Count from './components/Count'
import Person from './components/Person.vue'
export default{
name: 'App',
components:{Count,Person},
}
</script>
<style scoped>
</style>
vuex模块化+namespace
模块化+命名空间
目的: 让代码更好维护。让多种数据分类更加明确
修改store.js
//该文件用于创建Vuex中最为核心额store
import { setTimeout } from 'core-js';
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
Vue.use(Vuex);
//求和功能相关的配置
const countOptions = {
namespaced: true,
actions:{
addOdd(context,value){
if(context.state.sum % 2){
context.commit('ADD',value)
}
},
addWait(context,value){
setTimeout(()=>{
context.commit('ADD',value)
},500)
}
},
mutations:{
ADD(state,value){
state.sum+=value;
},
CUT(state,value){
state.sum-=value;
},
},
state:{
sum:0,
school: '理工',
subject:'Vue',
},
getters:{
bigSum(state){
return state.sum*10
}
}
}
//人员管理相关的配置
const personOptions = {
namespaced: true,
actions:{
addPersonWang(context,value){
if(value.name.indexOf('王')===0){
context.commit('ADD_PERSON',value)
}else{
alert("添加的人必须姓王!")
}
}
},
mutations:{
ADD_PERSON(state,value){
state.personList.unshift(value)
}
},
state:{
personList:[
{id:'001',name:'张三'},
]
},
getters:{
firstPersonName(state){
return state.personList[0].name
}
}
}
//创建并暴露store
export default new Vuex.Store({
modules:{
countAbout:countOptions,//可以简写
personAbout:personOptions
// personOptions//简写
}
})
开启命名空间后,组件中读取state数据:
//直接读取
this.$store.state.countAbout.sum
//借助mapState
...mapState('countAbout',['sum','school','subject']),
...mapState('personAbout',['personList']),
开启命名空间后,组件中读取getter数据
//直接
this.$store.getters['personAbout/firstPersonName']
//借助mapGetters
...mapGetters('countAbout',['bigSum'])
开启命名空间后,组件中调用dispatch
//直接
this.$store.dispatch('personAbout/addPersonWang',personObj)
//借助...mapActions
...mapActions('countAbout',{incrementOdd:'addOdd',incrementWait:'addWait'})
开启命名空间后,组件中调用commit
//直接
this.$store.commit('personAbout/ADD_PERSON',personObj)
//借助
...mapMutations('countAbout',{increment:'ADD',decrement:'CUT'}),
vue-router路由
route路由
router路由器
- 路由就是一组key-value的对应关系
- 多个路由,需要经过路由器的管理
vue-router的理解
vue的一个插件库,专门用来实现SPA应用
对SPA应用的理解
- 单页Web应用(single page web application,SPA)
- 整个应用只有一个完整的页面
- 点击页面中的导航链接不会刷新页面,只会做页面的局部更新
- 数据需要通过ajax请求获取
路由分类
前端路由:
- 理解:value是component,用于展示页面内容
- 工作过程:当浏览器的路径改变时,对应的组件就会显示
后端路由:
- 理解:value是function,用于处理客户端提交的请求
- 工作过程:服务器接收到一个请求时,根据请求路径找到匹配的函数来处理请求,返回响应数据。
基本路由
npm i vue-router
main.js
//引入VueRouter
import VueRouter from 'vue-router'
//应用插件
Vue.use(VueRouter)
新建router文件夹
在router文件夹下新建index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
import About from '../components/About.vue'
import Home from '../components/Home.vue'
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
path: '/about',
component: About
},
{
path: '/home',
component: Home
},
]
})
// export default router
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)
// const demo = Vue.extend({})
// const d = new demo();
// Vue.prototype.x = d;
new Vue({
el: '#app',
render: h=> h(App),
router:router
})
App.vue
//使用切换路径
//vue中借助router-link实现路由的切换
<router-link to="/about" active-class="active">About</router-link>
<router-link to="/home" active-class="active">Home</router-link>
<router-link>替换<a>标签
active-class="active"激活时使用active属性
//在哪里显示?指定组件的呈现位置
<router-view></router-view>
一般在pages里面放路由组件,components放一般组件。
频繁切换路由组件时,会被频繁的挂载-销毁
路由组件上$route
是不同的,$router
是相同的。整个应用只有一个$router
几个注意点
- 路由组件通常存放在
pages
文件夹,一般组件通常存放在components
文件夹 - 通过切换,"隐藏"了的路由组件。默认是被销毁掉,需要时再去挂载
- 每个组件都有自己的
$route
属性,里面存储看自己的路由信息 - 整个应用只有一个router,可以通过组件的
$router
属性获取到。
嵌套(多级)路由
配置路由规则,使用children配置项:
index.js
//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
import About from '../components/About.vue'
import Home from '../components/Home.vue'
import News from '../components/News.vue'
import Message from '../components/Message.vue'
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
path: '/about',
component: About
},
{
path: '/home',
component: Home,
children:[//通过children配置子级路由
{
// 子路由无需加/
path: 'news',
component: News,
},
{
// 子路由无需加/
path: 'message',
component: Message,
},
]
},
]
})
// export default router
跳转:(要写完整路径)
<router-link to="/home/news" active-class="active">News</router-link>
路由传参
路由传递query参数
//该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
import About from '../components/About.vue'
import Home from '../components/Home.vue'
import News from '../components/News.vue'
import Message from '../components/Message.vue'
import Detail from '../components/Detail.vue'
//创建并暴露一个路由器
export default new VueRouter({
routes:[
{
path: '/about',
component: About
},
{
path: '/home',
component: Home,
children:[
{
// 子路由无需加/
path: 'news',
component: News,
},
{
// 子路由无需加/
path: 'message',
component: Message,
children:[
{
path: 'detail',
component: Detail,
}
]
},
]
},
]
})
// export default router
传递参数
//跳转路由并携带query参数,to的字符串写法
<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>
//跳转路由并携带query参数,to的对象写法
<router-link :to="{
path:'/home/message/detail',
query:{
id:m.id,
title:m.title
}
}">
{{m.title}}
</router-link>
接收参数
$route.query.id
$route.query.title
命名路由
作用: 可以简化路由的跳转
如何使用
- 给路由命名
export default new VueRouter({
routes:[
{
name:'guanyu',
path: '/about',
component: About
},
{
path: '/home',
component: Home,
children:[
{
// 子路由无需加/
path: 'news',
component: News,
},
{
// 子路由无需加/
path: 'message',
component: Message,
children:[
{
name:'xiangqing'
path: 'detail',
component: Detail,
}
]
},
]
},
]
})
- 简化跳转
//跳转路由name写法
<router-link :to="{
name:'xiangqing',
query:{
id:m.id,
title:m.title
}
}">
{{m.title}}
</router-link>
//跳转路由name写法
<router-link :to="{name:'guanyu'}">{{m.title}}</router-link>
params参数
配置路由,声明接收params参数
{
// 子路由无需加/
path: 'message',
component: Message,
children:[
{
path: 'detail/:id/:title',
component: Detail,
}
]
},
传递参数
<router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>
//跳转路由并携带params参数,to的对象写法
//携带params参数必须使用name,不允许使用path
<router-link :to="{
name:'xiangqing',
params:{
id:m.id,
title:m.title
}
}">
{{m.title}}
</router-link>
特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
接收参数
$route.params.id
$route.params.title
路由的props配置
作用:让路由组件更方便的收到参数
{
// 子路由无需加/
path: 'message',
component: Message,
children:[
{
path: 'detail/:id/:title',
component: Detail,
// props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件
// props: {a:1,b:'hello'}
// props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件
// props:true,
// props的第三种写法,值为函数,
props($route){
//$route---{id:$route.query.id,title:$route.query.title}正常写法
//{query}---{id:query.id,title:query.title}
//{query:{id,title}} ---{id,title}
return {id:$route.query.id,title:$route.query.title}
}
}
]
},
组件中接收参数
props:['id','title']
router-link的replace属性
完整写法:
<router-link
:repalce="true"
:to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>
简写模式:
<router-link
repalce
:to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>
作用:
- 控制路由跳转时操作浏览器历史记录的模式
浏览器的历史记录有两种写入方式:
分别为push
和replace
,push
是追加历史记录,replace
是替换当前记录。路由跳转时候默认为push
如何开启replace
模式:<router-link replace......>News</router-link >
编程式路由导航
作用:
不借助<router-link></router-link>
实现路由跳转,让路由跳转更加灵活!
两个api
pushShow(m){
this.$router.push({
name:'xiangqing',
params:{
id:m.id,
title:m.title
}
})
},
replaceShow(m){
this.$router.replace({
name:'xiangqing',
params:{
id:m.id,
title:m.title
}
})
}
绑定事件:@click="pushShow(m)"
@click="replaceShow(m)"
前进后退
back(){
this.$router.back()
},
forward(){
this.$router.forward()
}
test(){
this.$router.go(2)
//前进两步
//可前进可后退
}
缓存路由组件
作用:让不展示的路由组件保持挂载,不被销毁!
<keep-alive include="News">
//最好添加include="News"属性,只管include里的路由组件名
<router-view></router-view>
</keep-alive>
<keep-alive :include="['News','Message']">
//最好添加include="News"属性,只管include里的路由组件名
<router-view></router-view>
</keep-alive>
两个新的生命周期钩子
作用: 路由组件所独有的两个钩子,用于捕获路由组件的激活状态!
activated(){
},//激活
deactivated(){
}//失活
activated
路由组件被激活时触发
deactivated
路由组件失活时触发
全局前置_路由守卫
全局前置路由守卫
-
初始化的时候被调用
-
每次路由切换之前被调用
index.js
to.path或to.name
router.beforeEach((to,from,next)=>{
if(to.path === '/home/news' || to.path==='/home/message'){
if(localStorage.getItem('school')==='atguigu'){
next()//放行
}
}
})
在meta里配置
index.js
export default new VueRouter({
routes:[
{
name:'guanyu',
path: '/about',
component: About,
meta:{isAuth:false}
},
]
})
router.beforeEach((to,from,next)=>{
if(to.meta.isAuth){
......
}
})
全局后置_路由守卫
index.js
export default new VueRouter({
routes:[
{
name:'guanyu',
path: '/about',
component: About,
meta:{isAuth:false,title:'主页'}
},
]
})
router.afterEach((to,from)=>{
document.title = to.meta.title || '硅谷系统'
})
路由守卫:
作用: 对路由进行权限控制
分类: 全局守卫,独享守卫,组件内守卫
独享路由守卫
只有前置独享路由守卫没有后置独享路由守卫
前置独享路由守卫配合全局后置守卫
export default new VueRouter({
routes:[
{
name:'guanyu',
path: '/about',
component: About,
meta:{isAuth:false,title:'主页'}
beforeEnter((to,from,next)=>{
...
})
},
]
})
组件内路由守卫
组件内:
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next){
...
next()
}
//离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeave(to,from,next){
...
next()
}
路由器的两种工作模式
history模式与hash模式
Vue的两种前端路由模式:hash和history
http://localhost:8080/students/#/adfaf/iinnnh
#后面的hash不会传递给后端服务器
vue-router
默认 hash 模式,还有一种是history模式。
默认是hash模式,修改模式使用mode修改
//创建并暴露一个路由器
export default new VueRouter({
mode: 'history',
})
-
对于一个url来说,什么是hash值?-----#及其后面的内容就是hash值
-
hash值不会包含在HTTP请求中,即:hash值不会带给服务器
-
hash模式:
- 地址中用于带着#号,不美观
- 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法
- 兼容性较好
-
history模式:
- 地址干净、美观
- 兼容性和hash模式相比略差
- 应用部署上线时需要后端人员支持,解决刷新页面服务端404问题
工程上线
打包工程:
npm run build
打包出来的文件部署在服务器
node express
打开文件夹
npm init
npm i express
node server
刷新浏览器会把history模式当成路径!
但是hash不会存在此问题!
history模式问题解决
后端解决!进行匹配
npm网址搜索connect-history解决nodejs
nginx也可解决
Vue UI组件库
移动端常用UI组件库
2 cube-ui Document (didi.github.io)
5 Vant - 轻量、可靠的移动端组件库 (gitee.io)
PC端常用UI组件库
2 iView - A high quality UI Toolkit based on Vue.js (iviewui.com)
4 Ant Design of Vue - Ant Design Vue (antdv.com)
Element UI使用
1、安装
npm i element-ui
2、main.js
引入Element UI组件库
import ElementUI from 'element-ui';
引入Element UI样式
import 'element-ui/lib/theme-chalk/index.css';
应用Element UI
Vue.use(ElementUI);
使用即可
Element UI按需引入
但是会把全部样式都引入,我们只需几个,
此时我们不要引入组件库,样式,不应用Element UI
借助 babel-plugin-component,我们可以只引入需要的组件,以达到减小项目体积的目的。
首先,安装 babel-plugin-component:
npm install babel-plugin-component -D
修改babel.config,js文件
module.exports = {
// 预设
presets: [
'@vue/cli-plugin-babel/preset',
["@babel/preset-env", { "modules": false }]
],
plugins: [
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
]
}
只希望引入部分组件,比如 Button 和 Select,那么需要在 main.js 中写
import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';
Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
/* 或写为
* Vue.use(Button)
* Vue.use(Select)
*/
根据引入的部分组件,样式自己分析加入