内容较多需要分几部
一.vue2面试题 - 生命周期有哪些?发送请求在created还是mounted?
1.1.生命周期有哪些
vue2.X系统自带有8个
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeDestroy
destroyed
1.2.进入组件执行哪些生命周期
beforeCreate
created
beforeMount
mounted
1.3在created中如何获取dome
只要异写异步代码,获取dom在异步中获取的就可以
列
定时器方法
setTimeout(()=>{
获取dome的方法
})
vue自带nextTick方法
this.$nextTick(res=>{
获取dome的方法
})
1.4为什么发送请求不在beforeCreate里?
如果请求是在methods封装好的,在beforeCreate掉用的时候是拿不到methods里面的方法的
1.5beforeCreate和created有什么区别
beforeCreate中没有$data
created中有$data
created中是可以拿到methods中的方法的
1.6.父组件引入子组件生命周期执行顺序
父组件引入了子组件,会先执行父组件的前3个生命周期,再执行子组件的4个生命周期
父:beforeCreat、create、beforeMount
子:beforeCreate、create、beforeMount、mounted
...
父:mounted
1.7发送请求在created中mounted?
这个问题需要看具体情况,按照上面的父组件引入子组件的顺序来看,
如果需要优先加载子组件内容需要再mounted中,如果组件间没有依赖关系,在哪个都可以
1.8加入keep-alive组件会执行哪些生命周期
如果使用了keep-alive组件,当前的组件会额外增加两个生命周期(系统8+2)
activated 进入到组件 激活时
deactivated 销毁时
如果加入keep-alive第一次进入会执行5个生命周期
beforeCreate
created
beforeMount
mounted
activated
1.9第二次或者第N次进入组件会执行哪些生命周期
activated
如果没加入keep-valive会永远执行
beforeCreate
created
beforeMount
mounted
2.0你在什么情况下使用过哪些生命周期,说一说生命周期的使用场景
created 单组件请求
mounted 同步获取dom, 如果子组件先请求父组件再请求
activated 判断id是否相同,如果不相同发起请求
deactivated 关闭页面记录视频播放时间,初始化的时候从上一记录开始
二.关于组件
2.1组件传值(通信)的方式
父传后代 (后代拿到了父的数据)
1.子组件通过props来接受父的传参
props:{
str1:{
type:String,
default:''
}
}
*这种方式父传子方便,但是传孙子背比较困难,并且不能修改父组件中的数据*
2.子组件直接使用父组件中的数据
子组件通过 this.$parent.xxx使用父组件中的数据
*子组件可以直接修改父组件中的数据*
*缺点:这可能会破坏组件的封装性和可维护性。*
3.依赖注入
优势:父组件可以直接向某个后代组件传递参数,(不需要一级一级的找)
后代传父(父拿到了后代的数据)
1.子组件传给父组件
子组件自定义事件 this.$emit('事件名字',传值)
父组件 <组件名 @事件='事件名字'> </组件名>
在methods中使用
2.
平辈之间传值(兄弟可以拿到数据)
2.2父组件直接修改子组件中的值
1. 使用this.$children
注意this.$children获取得是一个数据使用的时候应该: this.$children [索引]
* 繁琐 *
2. <组件名 ref='命名'></组件名>
this.$refs.命名.xxx = 'yyyyy'
2.3子组件如何修改父组件中的值
可以使用 this.$parent.xxx 获取到父组件中的值并修改
2.4如何找到父组件
this.$parent
2.5如何找到根组件
this.$root
2.6keep-alive
keep-alive是什么: 用来缓存当前组件的
2.7slot/插槽
1.匿名插槽:(没有名字)
子组件
<div>
<div>返回</div>
<slot></slot>
</div>
<组件名> <div style='color:pink'>温馨提示</div></组件名>
注意: 匿名插槽中的slot代表的是 组件的包括的所有内容
2.具名插槽(有名字)
子组件
<div>
<slot name="title"></slot>
<div>返回</div>
<slot name="text"></slot>
</div>
<组件名>
<template #title>
<h2 style="color: pink">标题</h2>
</template>
<template #text>
<div style="color: pink">温馨提示</div>
</template>
</组件名>
注意: 名字需要在template标签中
3.作用域插槽(传值)
子组件
<div>
<slot name="title"></s