Front-end vue (h5, WeChat applet) interview questions are continuously updated

vue2 interview questions

1. Explain event capture and event bubbling

  1. The concept of events : events are some specific interactive moments that occur in documents or browser windows. Event flow refers to the order in which events occur.
  2. Event capture : from outside to inside, events propagate from the outermost layer to the target element
  3. Event bubbling : from the inside out, the event propagates from the target element to the outermost layer
  4. The method to prevent event bubbling : event.stopPropagation()
  5. Prevent event default behavior : For example, a link click will automatically open a hyperlink, event.preventDefault();

2. Page reflow and redraw

  1. The browser's rendering process
    parses HTML, generates a DOM tree , parses CSS, generates a CSS tree , and combines the DOM tree and CSS tree to generate a rendering tree . According to the generated rendering tree , the page is reflowed to obtain the geometric information (position, size) of the element. According to the obtained rendering tree and geometric information , specific pixels are obtained, and the page is redrawn. Send the pixels to the GPU for display on the page.

  2. Reflow
    Constructs the rendering tree, which can combine the DOM element with its corresponding style to get the position and size of the corresponding dom element in the viewport. A reflow is triggered whenever the page layout changes

  3. Redraw
    Above we know the rendering tree and the reflow know the specific position and size information of the corresponding elements, and get the specific pixel value. At this time, the nodes on the rendering tree are rendered to the page according to the size and position information, which is called redrawing. Redrawing occurs whenever an element's background color, text color, border color, etc. are changed without affecting its surrounding or internal layout

  4. Performance optimization
    Minimize page reflow and redrawing

3. Enter the url to the browser to display the page. What happened?

  1. DNS domain name resolution: DNS resolves domain names into ip addresses
  2. Establish a TCP connection (three-way handshake): the purpose of three times is to establish reliable communication
  3. HTTP request: the browser sends the http request data to the server (client –> server)
  4. HTTP response: The server receives the client's request and returns the response result to the browser (server->client)
  5. Close the TCP connection: After the data transmission is completed, the connection is terminated through the fourth handshake
  6. Page rendering: The browser parses the response result and renders the page

4.px, em, rem, %, vw, vh

  1. px absolute pixel unit
  2. em refers to the size of the font-size of the parent element
  3. rem relative to the font-size of the root node html
  4. % Relative length unit, relative to the value of the size of the parent element
  5. vw is the unit relative to the width of the browser viewport
  6. vh Units relative to browser viewport height

5. Box model

  1. border-box: width and height of the box = width + padding + border
  2. The width and height of the content-box box = width

6.BFC

  1. Concept: BFC (Block Formatting Context) is an independently rendered area that is independent and does not affect external elements

  2. How to form BFC:
    1. Set floating float
    2. Set positioning, absolute or fixed
    3. Inline block display mode, inline-block
    4. Set overflow, namely hidden, auto, scroll
    5. Table cell, table-cell
    6. Elastic layout, flex

  3. What problems are solved by using BFC
    1. Solve margin collapse (vertical direction)
    2. Clear floating
    3. BFC can prevent standard flow elements from being covered by floating elements

7.div centered vertically and horizontally

  1. Center horizontally
    1. Set text-align:center for the parent element of the line-level element to match the line-height style
    2. Fixed-width block-level elements: set margin:auto style for itself
  2. Horizontal and vertical centering
    1. Use flex layout to center the internal block-level elements horizontally and vertically (display:flex;justify-content: center; align-items:center;) 2. Use positioning to achieve, parent element: position:relative; , child element: position: absolute;top:50%;left:50%;transform:translate(-50%,-50%); 3. Parent element: pos ition:relative; , child element: position: absolute; left: 50%, top: 50% + margin-left:-(half of its own width), margin-top:-(half of its own height) 4. Grid layout parent element setting display:grid, justify-content:center, align-content:center, grid-templaet-columns:100px, grid-template
    -rows
    :
    100px

8.js data type and type judgment

  1. Data type
    1. Basic data types: Number, Boolean, String, undefined, null
    2. Complex data types: arrays, objects, functions

  2. Data type judgment method
    1. typeof can detect string, Boolean, number, undefined, function, among which null and array (detected as object), the reason is that null and array are used as an empty object to reference 2. instanseof (recommended) is used
    to
    determine the specific type of object, usage: a instanse of A means to judge whether a is an instance of A, and the return value is a Boolean value 3. Array.isArray (array to be detected) can detect a data Whether it is an array 4.Object.prototype.toString.call(), it will return a string like "[object XXX
    ]
    "

9. Why use a unique key in v-for

1.若使用数组index当作key,当向数组中新插入一个元素后,这时会更新索引,对应着后面的虚拟dom的key都会全部更新,这些更新都是不必要的
2.如果没有key的话,默认的是就地复用的策略,如果数据项的顺序发生改变,vue不是移动dom来匹配数据项的改变,而是简单复用原来位置的每个元素,当比较到这个元素的值不一样的时候,将新的值放到该位置,以此类推,key的作用主要是为了高效的更新虚拟DOM

10.px2rem prohibits some px to rem

#box {
    
    
   height: 44px                //用postcss-px2rem插件配置后相当于0.44rem
   width: 100%
   font-size: 24px;/*no*/      //如果不想用插件转换可以用/*no*/标识符
}

11. The life cycle of vue

Create: beforecreate, created

beforecreate:
第一个钩子,这个阶段的data、methods、computed以及watch的数据和方法不能被访问

created:
这个阶段完成数据观测,数据初始化完成,可以使用数据,更改数据
无法与dom进行交互,想要的话可以用过nextTick来访问,nextTick延迟回调,更新数据后立即操作dom

Mount: beforeMount, mounted

beforeMount:
发生在页面渲染之前,当前阶段虚拟Dom已经创建完成,即将开始渲染。
在此时也可以对数据进行修改,不会触发updated

mounted:
数据挂载到dom上,数据完成双向绑定,可以访问到dom节点,使用$refs属性对dom进行操作
补:第一次页面加载就会触发 创建和挂载钩子

update beforeUpdate, updated

beforeUpdate:
发生在更新之前,也就是响应式数据发生更新,虚拟dom重新渲染之前被触发
可以在当前阶段进行更改数据,不会造成重复渲染

uodated:
发生在更新完成以后,当前阶段组件dom已完成更新
需注意的是避免在此期间更改数据,因为这可能导致无限循环的更新

destroy beforeDestory, destroyed

beforeDestory:
发生在市里销毁之前,在当前阶段实例完全可以被使用
可以在这进行善后收尾工作,如清楚定时器

destroyed:
发生在实例销毁之后,这个时候只剩下了dom空壳。组件已被拆解,数据绑定被清除,监听被移出,子实例也统统被销毁

Replenish:

activited:
keep-alive专属,组件被激活时调用

deactivited:
keep-alive专属,组件被销毁时调用

12. The difference between v-show and v-if

v-if 只有条件为真的时候才会真正渲染标签,不适合频繁渲染
v-show 基于display切换 适合频繁渲染
不推荐v-if与v-for使用,因为会把每个元素都增加v-if,造成性能问题

13. Communication between components

1.父传子:
父组件使用 :参数名=要传递的参数 :num=1000
子组件使用props接收 (props:[属性名])
子组件接收的另一种方式:
props:{
    
    
	num:{
    
    
		type:NUmber,//数据类型
		required:true//必须传值
		default:{
    
    
			100
		},//默认携带的数字
	}
}


2.子传父
1.**传递**:在调用子组件的位置,添加自定义事件,子组件使用$emit传递数据

3.父组件调用子组件的方法获取子组件的参数
	父组件上面定义ref="child" 
	父组件里调用子组件的方法:this.$refs.child.showPhone() showPhone是子组件里面的方法
	父组件里获取到子组件的参数:this.$refs.child.phone phone是子组件里的变量


4.子组件直接调取父组件数据参数和方法
子组件中获取数据参数:this.$parent.parentData parentData为父元素的变量
子组件中获取方法:this.$parent.showParent() showParent为父元素的方法

14. The difference between computed and watch:

1. computed attribute

1.支持缓存,只在依赖的数据发生变化时,才会重新计算,得到的为一个数据结果
2.不支持异步,当computed内有异步操作时无效,无法监听数据的变化
3.使用方式
 - 模版
   用插值表达式{
    
    {
    
    计算属性名}}
 - 在实例内
   this.计算属性名
代码演示:
{
    
    
	data(){
    
    
	},
	methods:{
    
    },
	computed:{
    
    
		计算属性名1(){
    
    
			//对依赖的属性进行处理,且进行return
			return
		},
		计算属性2(){
    
    
			//对依赖的属性进行处理,且进行return
			return
		}
	}
}

2. watch monitoring

1.不支持缓存,每调用一次就计算一次
2.支持异步
3.用于监听data里面的数据是否被修改,一旦修改就可以执行一些其他的操作【方法】
4.在监听的时候,可以有二次参数,第一次参数为新数据,第二次为旧数据
5.高级监听:可以监听单数据、数组,但是当监听对象的时候,明明数据修改了,却没有触发监听,此时需要开启深度监听,watch只会监听第一层
{
    
    
data:{
    
    },
watch:{
    
    
	//监听器的作用就是监听数据是否发生了变化,变化后可以进行一些其他的操作
	//只要没有发生变化,就没有办法进行其他操作
	text(newValue,oldValue){
    
    
	},
	deep: true, // 是否深度监听
    immediate: true, // 是否在组件创建时立即执行回调函数
}
}

15. The $set method in vue

1.由于vue会在初始化实例的时候进行双向数据绑定,所以属性必须是在data对象存在才能让他响应,如果要给对象添加新的属性,此时新属性并没有进行上述过程,不是响应式的,所以会出现数据变化,页面不变的情况,此时需要用到$set
2.实例
myInfo:{
    
    
	name:'xiaohua',
	age:'18'
}
this.$set(this.myInfo,'age',24)

16. vue routing

1.概念:路由指的是应用程序中的一个页面,是一个js对象
2.vue-router路由模式有几种?
 - hash路由:在地址栏会有一个#号,hash发生变化的url都会被浏览器记录下来,浏览器的前进后退可以用
 - history路由:
   history ——利用了HTML5 History Interface 中新增的pushState() 和replaceState() 方法。提供了对历史记录进行修改的功能。它能让开发人员在不刷新网页的情况下改变站点的 URL。History 有 URL 重定向问题,需要在服务端去配置 url 重定向,否则会报 404 错误。
3.router与route的区别
 - $router 路由实例,用来操作路由,包括push、replace、go、forward等方法,可以动态更改url,从而实现页面间的无刷新跳转
 - $route 路由信息对象 包括URL 路径、查询参数、路径参数等信息,path、params、query参数,只读对象
4.params传参与query传参
 - params传参类似于post请求,参数不会写到地址栏中(但是不能刷新),params只能配合name使用,假如使用动态路由'/user:id',则可以解决这个问题。
 - query传参类似于get传参,传过去的参数会显示在地址栏中,query既可以配合name使用,又可以配合path使用
 - 接收参数this.$route.query.id this.$route.params.id
// 路由配置
{
    
    
  path: '/user',
  component: User,
  props: {
    
     id: userId }
}
然后再目标页面里使用props去接收参数
// 在目标组件中获取传递的参数
export default {
    
    
  props: ['id'],
  created() {
    
    
    console.log(this.id)
  }
}
需要注意的是,在使用属性传参时,必须在目标组件中声明`props`,否则会抛出警告。同时,在使用属性传参时,可以使用`props: true`来将路由参数自动注入到目标组件的props中。
5.路由跳转
 - 声明式路由router-link to=`/path?参数名=参数值`
 - 编程式路由跳转 
   this.$router.push({
    
    name:'hello',query:{
    
    id:1}}this.$rouer.push({
    
    name:'hello',params:{
    
    id:1}})                                                                         						
   this.$router.push({
    
    path:'/hello',query:{
    
    id:1}}6.vue路由重定向 
 const routes = [
    {
    
     path: '/', redirect: '/index'},
    {
    
     path: '/index', component: index }
  ]
7.路由守卫
to为目标路由、from为当前路由 next()为跳转 可以用来做登录拦截
router.beforeEach((to, from, next) => {
    
    
        document.title = to.meta.title || '卖座电影';
        if (to.meta.needLogin && !$store.state.isLogin) {
    
    
            next({
    
    
                path: '/login'
            })
        } else {
    
    
            next(
            {
    
    
            	path:'/',
            	query:{
    
    
            		redirect: to.fullPath
            	}
            })
        }
    })
8.路由懒加载
 - 为什么需要懒加载,像vue这种单页面应用,如果没有懒加载,运用webpack打包后的文件将会异常的打,造成首页加载长时间的白屏,并且加载时间长。运用懒加载可以减少首页加载用时
 {
    
    
    path: '/login',
    name: 'Login',
    component: () => import('../views/login/login.vue')
  },
 9.路由监听
 watch:{
    
    $route(to,from){
    
     to代表的是当前路由,from指的是上一个页面路由,监听到路由变化后可以拿参数等东西 比如to.query.name等 }} 

17. Vue's built-in component keep-alive

页面切换的时候会进行销毁,当我们不想让它销毁的时候就需要用keep-alive包裹着组件
在组件切换过程中将状态保留在内存中,防止重复渲染dom,减少加载时间以及性能消耗,提高用户体验
根据条件缓存页面
APP.js页面
 <keep-alive>
    <!-- 添加meta的则添加 keep-alive -->
    <router-view v-if="$route.meta.keep"></router-view>
 </keep-alive>
 <!-- 不添加 -->
 <router-view v-if="!$route.meta.keep"></router-view>
路由页面给需要的添加meta
{
    
    
    path: '/',
    name: 'home',
    alias: '/home',
    components:{
    
     home },
    meta:{
    
    
      keep:true //需要缓存
    }
  },

Front-end logic combing

1.后端返回msg、stream、audioSrc
data:msg,audioList:[] (组件上接收这个音频参数列表,当第一个音频播放完以后自己去拉)
let obj = {
    
    	
	user_id:1,
	message:this.data.msg + receivedData.data.content,
	kind:kind == 99 ? 0 : kind,
	buttons:kind == 4 ? buttons_list : receivedData.data.buttons,
    type:'text',
    chatType:'audio',
    stream:stream
}
this.data.videoContext1.stop() //停止视频播放
let messgaeListArray = this.data.messageList
if(stream == 'begin'){
    
    
	this.data.msg = receivedData.data.content
	this.data.audioList = []
	obj.audioSrc = receivedData.audioSrc,
	messgaeListArray.push(obj)
	 this.setData({
    
    
         answerData:receivedData.data,
         // inputShow:false,
         messageList:messgaeListArray,
         audioSrc:res.audioSrc,
         isOrgin:false,
         isAudio:'audio',
         defaultVideo:false,
     })
}else if(stream == 'middle'){
    
    
	this.data.audioList.push(receivedData.audioSrc)
	messgaeListArray[messgaeListArray.length - 1] = obj
	this.setData({
    
    
        messageList:messgaeListArray
    })
}else if(stream == 'stop'){
    
    
	this.data.audioList.push(receivedData.audioSrc)
	messgaeListArray[messgaeListArray.length - 1] = obj
	this.setData({
    
    
        messageList:messgaeListArray
    })
}

//子组件
if(this.data.chatType == 'audio' && this.data.stream == 'begin'){
    
    
	if(this.data.myaudio){
    
    
		this.data.myaudio.stop()
	}
	this.openAudio()
}
//第一个音频播放完的操作
this.data.myaudio.onEnded(() => {
    
    
   this.data.audioList.forEach(item=>{
    
    
   	  this.data.myaudio.src = item
   	  this.data.myaudio.play()
   })
   if(this.data.stream == 'stop'){
    
    
   		this.triggerEvent('showTalkSilenceVideo')
   }
    // console.log('音频自然播放结束事件');
});

Guess you like

Origin blog.csdn.net/weixin_42631244/article/details/129753248