Vue interview related questions

Vue interview related questions

  1. keep-alive

    • vue system comes with a component whose function is to cache components, so that components can remain attached and not be destroyed
  2. The difference between v-show and V-IF

    • Different forms of presentation
      • DOM elements not displayed by v-if are removed directly
      • The v-show element is hidden, but it still exists
    • Different usage scenarios
      • v-if is suitable for scenarios with low switching frequency
      • v-show is applicable to scenarios with high switching frequency
  3. Priority of v-if and v-for

    • v-for has higher priority than v-if
    • It is embodied in the source code: function genElement
  4. nextTick

    • Get the updated dom content
    • nextTick() asynchronous operation
    • Usage scenario: this The ¥ nextTick() method is mainly used in data change and dom change application scenarios. Because data and dom rendering in vue are asynchronous, operations such as making dom structure change with data should be put into this n e x t T i c k ( ) of return transfer letter number in . c r e a t e d ( ) in send use of square method Hour , d o m still no have Configure dye , as fruit this Hour stay The hook son letter number in enter that 's ok d o m Fu value number according to ( or person his it d o m exercise do ) Hour nothing different to Apprentice work , place with , this Hour t h i s . In the callback function of nextTick(). When the method used in created() is used, the dom has not been rendered. If dom assignment data (or other dom operations) is performed in this hook function, it is futile. Therefore, this In the callback function of nextTick(). When the method used in created() is used, the dom has not been rendered. If dom assignment data (or other dom operations) is performed in this hook function, it is futile. Therefore, this nextTick() will be widely used, and the hook function of mounted() corresponding to created() will not render data until dom is fully rendered, so there will be no rendering problem when dom is operated in mounted().
  5. scoped

    • Make the style effective in this component without affecting other components
    • Principle: add custom attributes to nodes, and then add styles according to the attribute selector
  6. Parent component to child component

    //In parent component
    <son  xxx:'msg(Values passed to child components)'></son>
    
    //In subgroup components
    props:['xxx']
    //Strict acceptance
    props:{
    	xxx:String
    }
    
    //Second method slot
    
    //In parent component
    <Category>
        <div> Default contents of slots</div>
    </Category>
    //In subcomponents
    <slot> Default contents of slots </slot>
    
  7. Pass the child component to the parent component

    // In subcomponents
    this.$emit("Custom event name",this.msg)
    
    //In parent component
    <son v-on:Custom event name in subcomponent='getval' ></son>
    methods:{
    	getval(msg){
    		console.log(msg)
    	}
    }
    
  8. Transfer value between brothers

    • Global event bus (applicable to communication between all components)
    //In mian Install the global event bus in JS
    beforecreate(){
    	//this refers to the vm currently applied
    	vue.prototype.$bus = this  	
    }
    //receive data 
    mounted(){
    	this.$bus.$on('xxx',(data)=>{
    			console.log(data)
    		})
    }
    //Provide data
    this.$bus.$emit('xxx', data)
    
    //Destroy event
    beforeDestory(){
    	this.$bus.$off('xxx')
    }
    
    • Subscription and publication of messages (applicable to communication between all components)
    // Install pubsub:npm I pubsub js
    // Import PubSub from'pubsub js'
    
    //receive data 
    mounted(){
    	this.pid = pubsub.subscribe('xxx',(data)=>{
    		console.log(data)
    	})
    }
    
    //Provide data
    pubsub.publish('xxx',data)
    
    //Destroy event
    beforeDestory(){
    	pubsub.unsubscribe(pid)
    }
    
  9. computed methods

    • computed has cache
    • methods no cache
  10. computed watch

    • computed can calculate the change of a property. If a value is changed, the calculated property will listen and return
    • watch is that the internal code will be executed only when the currently monitored data changes
  11. Priority of data & props

    • props ==> methods ==> data ==> computed ==> watch
  12. ref

    • To get dom's (similar to doucumen.getElementById)
    <img ref='imgs' />
    
    console.log(this.$refs.imgs)       
    

route router

1. definitions

  • Routing: a route is a set of mapping relationships (key value). Multiple routes need to be managed by a router
  • Front end Routing: key is the path and value is the component

2. usage

  • Install Vue router, command: npm i vue router

  • Application plug-in: vue Use (vueroter) write in the main function

  • Write router configuration items

  • //Create a router folder and a new file index js
    //Introducing vueroter
    import vueRouter from 'vue-router'
    //Introducing routing components
    import School from './components/route'
    import Home from './components/route'
    
    //Create router instance objects and manage groups of routes
    const router = new VueRouter({
        routers:[
             {
                 path:'/School',\
                 component:School
                 children:[
                	{
                 		path:'new'        adopt children Configure sub route and secondary route
                 		component:News    Components do not need quotation marks     
            		 }
                 ]
             },
            {
                path:'/home',\
                component:Home 
            }
        ]
    })
    //Expose router
    export default  router
    
    //Shorthand create and expose a router
    // Create and expose a router
    export default new VueRouter({
        routes:[
            {
                path:'/school',
                component:School
            },
            {
                path:'/home',
                component:Home
            }
        ]
    })
    
  • Introduce the router into the main function

    • import router from ‘./ router/index.js' (index.js can be omitted)
  • Realize switching (active class can configure the highlighted style)

    • <router link active class= "active" to= "address" </router-link
  • Display at designated position

    • <router-view </router-view
  • matters needing attention

    • Routing components are usually placed in the pages file
    • By switching, the components are destroyed by default and can be mounted when necessary
    • Each component has its own $route attribute, which stores its own routing information
    • There is only one router in the whole application, which can be found through the $router attribute of the component.

3. named route

  • Can simplify route jump
  • Add a name parameter at the same level as path
  • Jump

4. query parameter of router

  • Jump and carry query parameters
Jump and carry query parameter,to String writing of
//<router link to= "/home? Id=666&title= hello" > jump to </router link> fixed parameters

//Template string writing variable parameter
<router-link :to=" `/home?id=${m.id}&title=${m.title} `">Jump</router-link>

//Jump and carry the query parameter, the object writing method of to
<router-link
             :to="{
                  path:'/home',
                  query:{
                  	id:m.id,
                  	title:m.title
                  }
                  }"
             >Jump</router-link>

//Target component receiving parameters
$route.query.id
$route.query.title

5. params parameter of router

// params parameter template string writing variable parameter
<router-link :to=" `/home/${m.id}/${m.title} `">Jump</router-link>

//The route jumps and carries the params parameter. The object writing method of to
<router-link :to="{
    name:school,         //name is required
    params:{
        id:m.id,
        title:m.title
                  }
                  }">
    		Jump
    <router-link>
        
//Routing configuration
        routes:[
        	{
        	name:'school',
        	path:'/school/:id/:titile',  //Tag id and title 
        	component:School
        }
        ]
        
//Target component receiving parameters
$route.params.id
$route.params.title

6. props configuration of routing

//Routing configuration
routes:[
    {
    name:'school',
    path:'/school/:id/:titile',  //Tag id and title 
    component:School

    //Props is the first way to write values, and all key values will be written in props
	//props:{a:1,b:'hello'}

	//The second way to write props is Boolean. If the Boolean value is true, all params received by the routing component will be
					Parameters, in props In the form of School assembly
	//props: true

	//The third way to write props is function (callback function, which will be executed without calling)
	//The key values of each group of objects returned by this function will be passed to the School component in props
	//props($route){
		retrun {
			id:$route.query.id,
			title:$route.query.title}	
	}
}
]

// Implement routing components
<router-link></router-link>

// In the School routing component
<template>
</template>
<script>
    export default {
        name:'School',
        //The first props writing method
        //props:['a','b']
        
        //The second props writing method must receive params parameters
        //props:['id','title']
        }
    	
    	//The first props writing method
        //props:['id','title']
    }
</script>

7. replace attribute of

  • Function: control the browser history mode during route jump
  • push: appends the history, which can be returned
  • Replace: replace the current record. Cannot return
  • <router link replace/push > the default is push

8. programming route navigation

  • Function: make route jump more flexible without the help of jump
<script>
    methods:{
        pushShow(Can transfer parameters){
           this.$router.push({
            name:'Destination route',
            Parameters of transmission belt
			 }) 
        },
        replaceShow(){
            this.$router.replace({
                name:'Destination route',
                 Parameters of transmission time band
            })
        },
        back(){
            this.$router.back()
        },
        forward(){
            this.$router.forward()
        }
        goText(){
            //Parameter: if it is an integer, it means forward; if it is a negative number, it means backward
            this.$router.go(parameter)
        }
    }
</script>

9. cache routing component

  • Function: keep the routing components that are not displayed attached and not destroyed.
<keep-alive include="['Component name 1','Component name 2']">  
    <router-link></router-link>
</keep-alive>

10. routing lifecycle

  • Function: two hooks unique to the routing component, which are used to capture the activation status of the routing component

  • Triggered when the activated routing component is activated

  • Triggered when the deactivated routing component is deactivated

//Timer creation and destruction in routing
activated(){
	this.timer = setInterval(()=>{
		this.opacity -= 0.01
		if(this.opacity <= 0) this.opacity = 1
	},16)
},
deactivated(){
          clearnInterval(this.timer)                  
      	}               

11. route guard

  • Global routing guard
const router = new VueRouter({
    routes:[
        {
        name:'school',
        path:'/school/:id/:titile',  //Tag id and title 
        component:School,
		//Routing meta information isAuth: a value of true indicates that permission judgment is required
        meta:{isAuth:true,title:'full name'},  
		//Exclusive route guard
		beforeEnter:((to,from,next)=>{
			if(to.meta.isAuth){ //Determine whether the current route needs permission control
				if(localStroge.getItem('name') === 'lz'){
					next()
				}else{
					alert('Wrong name, no permission to view!')
				}
			}else{
				next()
			}	
			})
        }
    ]
})

//The global pre route guard is called when initializing, and it is called before switching routes every time
router.beforeEach((to,from,next)=>{
	if(to.meta.isAuth){ //Determine whether permission control is required for the current route
		if(localStroge.getItem('name') === 'lz'){
			next()
		}else{
			alert('Wrong name, no permission to view!')
		}
	}else{
		next()
	}	
})

//It is called when the global post route guard is initialized, and it is called after each route switching
router.afterEach((to,from)=>{
	doucument.title = to.meta.title || 'lz'  
})

export default router
  • Guard inside the assembly
//Entry guard: it is called when entering this component through routing rules
beforeRouteEnter(to,from,next){}
//Leave guard: called when leaving the component through routing rules
beforeRouteLeave(to,from,next){}
  1. Two working modes of router
  • mode: hash/history //routes:[{mode:}]

  • hash

    • The address always carries \
    • Good compatibility
    • The hash value will not be included in the HTTP request, and the hash value will not be passed to the server
  • history

    • Address clean none#
    • Poor compatibility compared with hash
    • When the application deployment goes online, it needs the support of back-end personnel to solve the 404 problem of refreshing the page server
  • Match front-end route or back-end route

    • npm website connect history API fallback
    • nginx

end summary

1. Differences between query and params

  • query uses path to write the parameter passing address, while params uses name to write the parameter passing address
  • The parameters will not disappear when query refreshes the page, while the parameters will disappear when params refreshes the page
  • The parameters passed by query will be displayed in the url address bar, while the parameters passed by params will not be displayed in the address bar.

Tags: Javascript Vue.js Front-end

Posted by dotbands on Fri, 01 Jul 2022 21:53:12 +0530