第三章
3.1 初始化脚手架
3.1.1 说明
-
Vue 脚手架是 Vue 官方提供的标准化开发工具(开发平台)。
-
最新的版本是 4.x。
-
文档: https://cli.vuejs.org/zh/。
3.1.2 具体步骤
第一步(仅第一次执行):全局安装@vue/cli。 npm install -g @vue/cli
第二步:切换到你要创建项目的目录,然后使用命令创建项目 vue create xxxx
第三步:启动项目 npm run serve
备注: 1. 如出现下载缓慢请配置 npm 淘宝镜像:npm config set registry https://registry.npm.taobao.org 2. Vue 脚手架隐藏了所有 webpack 相关的配置,若想查看具体的 webpakc 配置, 请执行:vue inspect > output.js
3.1.3 模板项目的结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gHKJkElZ-1672906421794)(C:\Users\琳莉\AppData\Roaming\Typora\typora-user-images\image-20221208133248927.png)]
3.2 ref属性与props
3.2.1 ref
ref属性:1.被用来给元素或子组件注册引用信息(id的替代者)
2.应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
3.使用方式:
打标识:<h1 ref="xxx"></h1>
或<School ref="xxx"/>
获取:this.$refs.xxx
<template>
<div>
<h1 v-text="msg" ref="title"></h1>
<button ref="btn" @click="showDom">点我输出上方的DOM元素</button>
<MySchool ref="sch" name='北京大学' address='北京'/>
</div>
</template>
<script>
//引入School组件
import MySchool from './components/MySchool.vue'
export default {
name:'App',
data(){
return{
msg:'欢迎学习vue!'
}
},
components:{MySchool},
methods:{
showDom(){
console.log(this.$refs.title);//真实DOM元素
console.log(this.$refs.btn);//真实DOM
console.log(this.$refs.sch);//School组件的实例对象(vc)
}
}
}
</script>
3.2.2 props配置
功能:让组件接收外部传过来的数据
(1)传递数据
<Demo name="xxx" />
(2)接收数据
第一种 (只接收)
props:['name','sex','age'], //简单声明接收,用的多
第二种(限制类型)
//接受的同时对数据进行类型限制
props:{
name:String,
age:Number,
sex:String
第三种(限制类型,限制必要性,指定默认值)
//接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
props:{
name:{
type:String,//name类型为字符串
required:true//name是必要的
},
age:{
type:Number,
default:99//默认值
},
sex:{
type:String,
required:true
}
}
备注:props是只读,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求必须修改,那么就复制props的内容到data中一份,然后去修改data中的数据
如下:
MyStudent.vue
<template>
<div>
<h1>{{msg}}</h1>
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<h2>学生年龄:{{myAge}}</h2>
<button @click="updateAge">点击修改年龄</button>
</div>
</template>
<script>
export default {
name:'MyStudent',
data(){
return{
msg:'你好!',
myAge:this.age
}
},
methods:{
updateAge() {
this.myAge++
},
},
props:['name','sex','age'], //简单声明接收,用的多
</script>
App.vue
<template>
<div>
<!-- 引号内容原来传递的是字符串,加v-bind后引号内容变成js表达式 -->
<MyStudent name="星星" :age="18+1" sex="女"/>
<!-- MyStudent name="星星" age="18" sex="女"/> -->
</div>
</template>
<script>
//引入School组件
import MyStudent from './components/MyStudent.vue'
export default {
name:'App',
data(){
return{
}
},
components:{MyStudent},
}
</script>
3.3 mixin 混入
功能:可以把多个组件共用的配置提取成一个混入对象
使用方式:
第一步定义混合,例如
mixin.js
export const mixin ={
methods:{
showName(){
alert(this.name)
}
},
mounted() {
console.log('你好啊~')
},
}
export const mixin2 ={
data(){
return{
x:100,
y:200
}
}
}
第二步使用混合,例如
(1)全局混入:在main.js中输入Vue.mixin{xxx}
main.js
import Vue from 'vue'
import App from './App.vue'
import {mixin,mixin2} from './mixin'
Vue.config.productionTip=false
Vue.mixin(mixin)
Vue.mixin(mixin2)
new Vue({
el:'#app',
render:h=>h(App)
})
(2) 局部混入:mixins:[‘xxx’]
以MySchool.vue为例
<template>
<div>
<h2 @click="showName">学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
</template>
<script>
import {mixin,mixin2} from '../mixin.js'
export default {
name:'MySchool',
data(){
return{
name:'加里敦大学',
address:'加里敦',
x:666//就近原则,听你的
}
},
mixins:[mixin,mixin2],
mounted(){
console.log('你好啊~~~~~~~~~');//生命周期钩子都要
}
}
</script>
3.4 插件
功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据
定义插件——plugins.js:
export default {
install(Vue){
//全局过滤器
Vue.filter('mySlice',function(value){
return value.slice(0,4)
})
//定义全局指令
Vue.directive('fbind',{
//指令与元素成功绑定时(一上来)
bind(element,binding){
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element){
element.focus()
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
}
})
//定义混入
Vue.mixin({
data(){
return {
x:666,
y:888
}
}
})
//给Vue原型上添加一个方法(vc和vm都能用)
Vue.prototype.hello = ()=>{alert('hello!')}
}
}
使用插件——main.js
//引入插件
import plugins from './plugins'
//应用插件
Vue.use(plugins)
scoped样式
作用:让样式在局部生效,防止冲突,在App.vue中最好不要使用
写法:<style scoped>
,
3.5 Todo-list案例
1.添加
3.6 浏览器本地存储webStorage
存储内容大小一般支持5MB左右(不同浏览器可能还不一样)
浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。
1.相关API
(1) xxxxxStorage.setItem('key', 'value');该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。
(2) xxxxxStorage.getItem('person');该方法接受一个键名作为参数,返回键名对应的值。
(3) xxxxxStorage.removeItem('key');该方法接受一个键名作为参数,并把该键名从存储中删除。
(4)xxxxxStorage.clear()该方法会清空存储中的所有数据。
2.一些注意点
(1)SessionStorage存储的内容会随着浏览器窗口关闭而消失。
(2) LocalStorage存储的内容,需要手动清除才会消失(调用clear或者清除缓存)。
(3) xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。
(4)JSON.parse(null)的结果依然是null。
3.Todo-list的本地存储
JSON.stringify将Js对象或值转换为JSON格式化的字符串
JSON.parse将格式完好的json字符串转换为json对象
data(){
return {
//由于todos是MyHeader组件和MyFooter组件都在使用,所以放在App中(状态提升)
todos:JSON.parse(localStorage.getItem('todos')) || []
//初始化时如果有就读取,否则初始值为空数组
}
watch:{
todos:{
//watch中要配置深度监视deep,否则页面刷新已经勾选的就重置了,这是因为watch监视todos只会监视todos里面的元素,也就是每个对象的地址,但是对象属性的变化监测不到,但是加了deep就监视到了
deep:true,
handler(value){
localStorage.setItem('todos',JSON.stringify(value))
}
}
3.7 组件的自定义事件
1.一种组件间通信的方式,适用于:子组件 ===> 父组件
2.使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)
3.绑定自定义事件:
1.第一种方式,在父组件中:<Demo @hxx="test"/>
或 <Demo v-on:hxx="test"/>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法:使用@或v-on) -->
<Student v-on:aStudent="getStudentName" @demo="m1"></Student>
2.第二种方式,在父组件中:
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法:使用ref) -->
<Student ref="student" @click.native="show"/>
..........
mounted(){
this.$refs.student.$on('aStudent',this.getStudentName)//绑定自定义事件
}
3.若想让自定义事件只能触发一次,可以使用once
修饰符,或$once
方法
this.$refs.student.$on('aStudent',this.getStudentName)
this.$refs.student.$once('aStudent',this.getStudentName)//只触发一次
4.触发自定义事件:this.$emit('hxx')
5.解绑自定义事件this.$off('hxx')
methods:{
sendStudentName(){
//触发Student组件实例上的aStudent事件
this.$emit('aStudent',this.name)
this.$emit('demo')
},
unbind(){
// this.$off('aStudent') //解绑一个自定义事件
// this.$off(['aStudent','demo']) //解绑多个自定义事件
this.$off() // 解绑所有的自定义事件
}
}
6.组件上也可以绑定原生DOM事件,需要使用native
修饰符
<Student ref="student" @click.native="show"/>
7.注意:通过this.$refs.xxx.$on('hxx',回调)
绑定自定义事件时,回调要么配置在methods中,要么用箭 头函数,否则this指向会出问题
//1.使用箭头函数时,this指向App组件实例,否则就是Student(谁触发事件,this指向谁)
mounted(){
this.$refs.student.$on('aStudent',(value)=>{
console.log('App收到了学生名:'+value),
this.studentName = value
})//绑定自定义事件
}
//2.配置在methods中,比较简单,不用考虑this的指向问题
methods:{
getStudentName(value){
console.log('App收到了学生名:'+value),
this.studentName = value
},
mounted(){
this.$refs.student.$on('aStudent',this.getStudentName)//绑定自定义事件
}
3.8 全局事件总线
1.一种组件间通信的方式,可以实现任意组件间的通信
2.安装全局事件总线:
const vm = new Vue({
.......
beforeCreate(){
Vue.prototype.$bus = this //安装全局事件总线
}
.......
})
3.使用事件总线:
1.接收数据:A组件想要接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身
mounted(){
this.$bus.$on('hello',(data)=>{
console.log('我是School组件,收到了数据',data);
})
},
2.提供数据:this.$bus.$emit('xxx',数据)
4.最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件
beforeDestroy(){
this.$bus.$off('hello')
}
3.9 消息订阅与发布
报纸订阅预发布:1.订阅报纸:住址 2.邮递员送报纸:报纸
消息订阅与发布:1.订阅消息:消息名 2.发布消息:消息内容
1.一种组件间通信的方式,适用于任意组件间通信
2.使用步骤:
1.安装pubsub:npm i pubsub-js
2.引入:import pubsub from 'pubsub-js'
3.接收数据:A组想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身
methods(){
demo(data){.......}
}
........
mounted(){
this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
}
4.提供数据:pubsub.publish(‘xxx’,数据)
5.最好在beforeDestory钩子中,用pubsub.unsubscribe(pid)
去取消订阅
3.10 nextTick
1.语法:this.$nextTick(回调函数)
2.作用:在下一次DOM更新结束后执行其指定的回调函数
3.什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行
3.11 Vue封装的过渡与动画
1.作用:在插入、更新或移除DOM元素时,在合适的时候给元素添加样式类名
2、写法:
准备好样式:
元素进入的样式:
v-enter:进入的起点
v-enter-active:进入过程中
v-enter-to:进入的终点
元素离开的样式:
v-leave:离开的起点
v-leave-active:离开过程中
v-leave-to:离开的终点
使用<transition>
包裹要过度的元素,并配置name属性:
<transition name="hello">
<h1 v-show="isShow">你好啊!</h1>
</transition>
pubsub.publish(‘xxx’,数据)
5.最好在beforeDestory钩子中,用pubsub.unsubscribe(pid)
去取消订阅