Title, personal information, job search intention, professional skills, work experience, project experience, educational background
1, Vue knowledge points
1. Basic use
1.1 data driven
Concept: when the data changes, the user interface will follow the changes without modifying the dom manually
1.2 MVVM framework
MVVM framework mainly includes: it is an architecture design pattern, which is composed of Model, View and ViewModel
Model: data part
View: View section
ViewModel: intermediate bridge connecting View and Model (instance of vue)
Function: it realizes the function of separating data from View. When the data Model changes, ViewModel will listen to the change and notify the View to make the change. When the event of View is triggered, ViewModel can also event and let the Model respond.
Difficulty: the three elements of MVVM - responsiveness, template and rendering
2. Template syntax
2.1 dynamic binding between class and Style
Class:
Class Object syntax <div :class="{active: true}"></div> have active This class name <div :class="{active: isActive===0}"></div> The following judgment is true Just have active Class name Class Array syntax <div :class="[active?activeClass:'']"></div>active by true Just have activeClass Class name, otherwise it is empty
Style:
Style Object syntax <div :style="{fontsize: ph+'px'}"></div> <div :style="{color: active===item?'red':'pink'}"></div> Style Array syntax <div :style="[styleColor,styleSize]"></div> data() { styleColor: { color: 'red' }, styleSize: { font-size: '16px' } }
Style object syntax: style = "{color: 'Red', fontsize: Ph + 'PX'}"
Change:: class = "{color: select = = = item?'Red ':'pink'}" judge whether select is equal to item, positive red and false pink
3. Conditional rendering v-if and v-show
v-if is the real conditional rendering, which controls whether the element exists. If it is false, the element does not exist.
v-show controls display and hiding through the css attribute display.
If you need to frequently control the display and hiding of elements, use v-show to avoid a large number of DOM operations and improve performance; An element meets the conditions and changes less. Use v-if.
4. Calculated attribute computed
computed is an object in which a function can be defined, but this function can be used directly as an attribute.
Advantages: avoid too much logic in the template; It has the caching function. Unlike methods, which are executed every time, it will call the cached data. Only when the data on which the calculation attribute depends changes will it be re valued.
<div>{{fullName}}</div> computed: { fullName() { return this.firstname+this.lastname } }
5. Listener watch
The listening data changes. If the data changes, perform the corresponding operation. Allows asynchronous operations to be processed in a watch
Processing scenario: for asynchronous operations or operations with high overhead, deep listening can be enabled to listen to the object's properties. deep:true, but old value cannot be obtained
Difference between watch and computed:
-
watch: it is suitable for doing other things when a value changes. It handles asynchronous operations. A value affects multiple values
computed: it is derived from its dependent value. The dependent value changes and the corresponding value also changes. It is suitable for multiple values to affect one value
-
The computed calculation attribute has a cache function. If you can use the calculation attribute, try to use this as much as possible
-
watch is suitable for asynchronous operations or operations with high overhead
watch: { users: { immediate: true,//Execute immediately. Without this, it will not be executed during the first rendering. If it is added, the initialization will also execute the listener handler(newValue, oldValue) { this.totalcount = newValue.length + 'Number of people' } } } watch: { // watch monitors the change of uname and changes the value of message. It can also send other asynchronous requests uname(value) { this.checkUserName(value) this.message='In asynchronous requests' // Did some other asynchronous operations } } computed: { fullName() { return this.firstname+this.lastname // 2 values to get 1 value Be sure to return } }
5.1 events and parameters
5.1.1 event parameters
Event is native and the event is mounted to the current element
<button @click="add">+1</button> <button @click="down(2, $event)">+2</button> add(event){ console.log(event)// No parameters are passed and native event s are output } down(val, event){ // Formal parameters need to be defined to receive console.log(event) // Pass parameter output event }
6. Life cycle
6.1 three stages
- Mount phase (initialization related attributes, such as watch and methods): beforeCreate, created, beforeMount and mounted
- Update phase (change operation of element or component): beforeUpdate, updated
- Destruction stage (destroy related attributes): beforeDestroy, destroyed
beforeCreate(): The component instance has not been created before creation created(): After creation, the component initialization is completed, and various data can be used ajax Send asynchronous request to get data beforeMount(): Before mounting, rendering, updating, and virtualization are not performed DOM Complete, true DOM Not created mounted(): After mounting, real DOM After creation, you can access dom Element sends an asynchronous request to get data beforeUpdate(): Before updating, it is used to obtain various data status before updating updated(): After the update, all data are updated beforeDestroy(): It is used to process the clearing of some timers before destruction destroyed(): After destruction, the sub instance is destroyed and all event listeners are removed
7. Component development
7.1 component description
Split a page into multiple components, each of which has different functions.
Features: reusability, maintainability and combination
7.2 basic use
Vue.component('componentActive', {template: "<p>Minecraft</p>"}) // In case of hump naming, you need to use - to splice <component-active></component-active>
8. Use of slots
8.1. Basic slot
When components are used in the page, there can be no content in the component. If there is content, it is the content of the slot
<div id="app"> <alert-box>I insert in slot position</alert-box> </div> Vue.component("alert-box", { template: ` <div> <h1>Minecraft</h1> <slot>Default content</slot> // The above components use the default content if there is no content </div> ` })
Transfer the contents in the sub component label to the corresponding slot, and then transfer the whole sub component
8.2 named slot
The slot filling content of the corresponding name will be found. If there is no name, it will not be filled
< div slot = "header" > My insertion slot location < / div > < slot name = "header" > slot < / slot >
Note: we add the slot name to the template tag and embed multiple other tags in its tag to complete the layout
<template slot="header"> <div>I'm the one who inserted the content</div> <div>I'm inserting content two</div></template>
8.3. Scope slot
It is more flexible to expose the data of child components and specify different templates for parent components according to the data
Render render function
Vue.set .set
Vue.delete .delete
$on $emit
$once $off
r e f s v m . refs vm. refsvm.refs ref
Filter with parameters Qidong County
Mix in mixin
2, Vue router Foundation
1. Introduction to routing
- Back end routing
- Concept: return different contents according to different user URL requests
- Essence: the correspondence between the URL request address and the server resource
- SPA
- Ajax front-end rendering, front-end rendering improves performance
- SPA single page application, the whole web page has only one page, which can be updated locally through AJAx
- Core technology point: front end routing
- Principle 1: hash based on URL address
- Front end routing
- Concept: display different contents according to different triggering user events
- Essence: the correspondence between user events and event handling functions
2. Programming navigation
-
Declarative navigation: a way to navigate by clicking a link,
-
Programming navigation: realized by calling API, this$ router. push('/login')
// String (pathname) router push('/home')router. push({ path: '/home' }) // Object router Push ({Name: '/ user', params: {userid: 123}}) / / named route (pass parameter) router Push ({path: '/ Register', query: {uname: 'Lisi'}}) / / query with parameters / register?uname=lisi
3. Routing guard
1. Global front guard
router.beforeEach((to, from, next) => {})
To: which page to go to from: which page from next: continue execution
router.beforeEach((to,from,next) => {if(to.path == '/login' || to.path == '/register') { next()}else { alert('Please log in first, if not') next('/login')}})
Global post guard (generally not mentioned, global guard refers to front guard)
router.afterEach((to,from) => {})
The global post guard will not accept the next function, nor will it change the navigation itself
2. Exclusive guard
beforeEnter(to, from, next) {} only works on the added route
const router = new VueRouter({ routes: [{ path: '/foo', component: Foo, beforeEnter: (to, from, next) => { if(window.isLogin) { next() } else { next('/login?redirect=' + to.fullPath ) } } }]})
3. Guard in assembly
// beforeRouteEnter Before invoking the rendering component, you can't get this. The component instance is not mounted beforeRouteEnter (to, from, next) {if (window.isLogin) {next ()} else {next ('/login + + +)}} / / / when the current route changes, but when the former component is reused, it is called. The instance thisbeforerouteupdate (to, from, next) {next()} / / beforerouteleave leaves the route corresponding to the component and is called beforerouteleave (to, from, next) {next()}
4. Dynamically add routes
Syntax: this$ router. addRoutes([])
5. Routing component cache - keep alive
<keep-alive include="goods"> // Only works as a route cache for the goods component. You need to add the name attribute to the component to find it faster. < router View > < / router View > < / keep alive > / / keep alive has two hook functions. Activated and deactivated enter the keep alive cache page from other pages, and the activated hook function will be triggered to update and leave the cache page, Will trigger deactivated. When caching a page, clicking refresh will trigger: created -- mounted -- activated
6. Hash mode and History mode
-
In front-end routing, when the path changes, no request will be made to the server. Only when ajax is used will the request be sent to the server
-
Hash mode
https://www.baidu.com/#/showlist?id=123
In the hash mode, the path has #, and the content behind # is used as the routing address, which can be accessed through? Carry parameters
-
History mode
https://www.baidu.com/showlist/123
history mode is a normal path mode, which needs the corresponding support of the server
-
The difference between Hash and History
Hash mode: Based on the anchor point and onhashchange event, the value of the anchor point is used as the routing address, and the onhashchange event is triggered when the address changes
History mode: Based on the History API in HTML5, history Pushstate() and history replaceState()
7. Use of History mode
const router = new VueRouter({ mode: "history",// Default hash routes: [{path: '/ Login', component: login}]})
8. Nginx server
- Proxy server: the machine inside the LAN sends requests to the server on the Internet through the proxy server.
- Reverse proxy server: the server receives the request from the customer service side, then distributes the request to each specific server for processing, and then reports the result to the client.
- After clicking the refresh button in the browser, a request will be sent to the server. After receiving the request, the server finds that the accessed file is not found because some try is configured_ Files, all html directories will be indexed The content of the html page is returned to the browser. The browser processes it according to the routing, finds and renders relative to the component.
3, Vue router principle
1. Analyze how Hash and History work
- Hash: the # back of the URL is the path address. When the address changes, it will not send a request to the server, but trigger the hashchange event, record the current routing address, find the corresponding component according to the current routing address, and re render
- History: through history The pushstate() method changes the address bar, and the current address is recorded in the browser history. It will not send a request to the server, listen to the pop state event, find the changes of browser history operations, record the changed address, and find the corresponding component rendering according to the routing address.
The mode is basically similar: window location. Hash() directly assigns window location. Replace() instead calls window location. History. Pushstate() and window location. The replatstate () method, and the listening to modify the browser address bar in History is added in the constructor.
2. Routing configuration (dynamic routing, lazy loading)
routes: [ {path: '/user/:id', components: User, redirect: '/index'}, {path: '/feedback', component: () => import('../components/Feedback')}]
4, Vue responsive principle
1. Data driven
MVVM
2. Core principles of responsive
Vue2.x
Listening object, listening array, complex object, deep listening, defect
Disadvantages: 1. Deep monitoring requires recursion to the end and requires a large amount of one-time calculation
2: unable to listen for adding / deleting attributes (Vue.set/Vue.delete API does things)
3: unable to listen to the native array, special processing is required
-
defineProperty
// Vue2.x is through object Defineproperty data hijacking to change Single attribute let data = {MSG: 'hello'} // Data let vm = {} // vue instance / / data hijacking object defineProperty(vm,'msg',{ enumerable: true, configurable: true, get(){ // Get return data msg }, set(newValue){ if(newValue===data.msg){ return } data. msg=newValue document. querySelector('#app'). textContent=data. msg }})vm. msg='abc'console. log(vm.msg)
-
defineProperty listens for properties in an object
let data={msg: 'hello', count: 10} // (multiple attributes) let vm = {} // Instance proxydata (data) // Call function proxyData(data) { Object.keys(data).forEach(key => { // Object.keys() converts the object into an array and iterates over the object defineProperty(vm, key, { enumerable: true, configurable: true, get() { console.log('get', key, data[key]) // Different data reading methods return data [key]}, set (newvalue) {console.log ('set ', key, newvalue) if (newvalue ={ return } data[key] = newValue document.querySelect('#app').textContent=data[key] } }) })}vm.msg='hello word '/ / first trigger setconsole log(vm.msg) // Post trigger get
Vue3.x
// Vue3.x is through proxylet data = {MSG: 'hello', count: 0} let VM = new proxy (data, {get (target, key) {console.log ('Get key ', key, target [key]) return target [key]} set (target, key, newvalye) {console.log ('set key', key, newvalue) if (target [key] = = newvalue) {return} target [key] = newvalue document querySelector('#app'). textContent = target[key] }}) vm.msg = 'abc'console.log(vm.msg)
3. Publish subscriber mode
// Subscriber, publisher, signal center let eventhub = new vue() addtodo: function() {eventhub. $emit ('add todo ') // Publish} create: function() {eventhub. $on ('add todo ') // Subscription}
4. Componentization
5. vdom and diff
- vdom - simulate DOM structure with js, calculate the minimum variable and operate dom
- diff algorithm is the core and key part of vdom
- diff algorithm can be used in daily life, such as key
6. Template compilation
7. Render pass
8. Front end routing
5, vue interview Basics
1. computed and watch
- computed has a cache. The data it depends on has not changed and will not be recalculated
- watch listens to the reference type (object), cannot get oldValue, and has pointed to newValue
- The first time the watch is loaded, it will not be updated. You need to set the attribute immediate:true
2,v-for
-
v-for and v-if cannot be used together. The priority of v-for is higher than that of v-if. It will execute the loop before judging. It is unreasonable
<li v-if="flag" v-for="item in lists" :keys="lists.id"></li>
3. Parent child component communication - brother component communication
Parent child communication: props – e m i t transfer use father group piece ' t h i s . emit call parent component ` this Emit calls the parent component 'this emit`
Brother communication: o n set righteousness / on definition/ On define / emit call to define event$ on('onAdd', this.addtitle)
Call event$ emit('onAdd', this.title) addtitle(title){}
Destroy the custom event in beforeDestroy in time$ off('onAdd',this.addtitle)
// Event is a new Vue instance import Vue from 'Vue' export default new Vue {} import event from '/ Event '/ / import
4. Declaration period
5. $nextTick Vue is asynchronous rendering
Vue is rendered asynchronously. After the data is changed, the DOM node will not render immediately, and $nextTick will be triggered after DOM rendering to obtain the latest DOM node
addItem(){ this.list.push(data.name) thislist.push(data.name) // const ulElem = this.$ refs. ul1 // console.log(ulElem.childNodes.length) / / Vue is rendered asynchronously. If the data changes, the DOM will not render immediately. You need to use $nextTick(), which will call back this after the DOM rendering is completed$ nextTick(() => { const ulElem = this.$refs.ul1 console.log(ulElem.childNodes.length) })}
2. When the page is rendered, the data will be integrated and the extra data will be modified for rendering
6. Custom v-model data bidirectional binding
The essence of v-model is a v-bind and v-on syntax sugar. The syntax sugar of value+input method is customized through props+event attribute of model attribute
<input type="text" :value="text1" @input="$emit('change1', $event.target.value)">export default{ model: { props: 'text1', event: 'change1' }, props: { text1: String, default() {return ''} }}
7,slot
-
Basic usage:
The parent component uses the child component. The content in the child component label is usually not given. If it is given, it will replace the slot label content in the child component. If it is not given, the slot label content of the child component will be used by default
// father. vue<son> {{user.name}} </son>// son. vue<template> <a> < Slot > Default Content < / slot > < / a > < / template >
-
Scope slot:
Scope slot: the parent component can use the data defined in the child component, define the data through v-bind in the child component, and use the name to receive the v-slot definition in the parent component. When referencing: slotfather slotname. name
// father. vue<son> <template v-slot="slotFather"> {{slotFather.slotname.name}}// jack </template></son>// son. vue<template> <a> < Slot: slotname = "user" > Default Content < / slot > < / a > < / template > data() {return {user: {Name: 'Jack', age: 18}}
-
Named slot:
Only those with the same name will be able to communicate with each other
8. Dynamic components (less)
: is="val.type": used to render dynamic components
<div v-for="(val,key) in list"> <component :is="val.type"></div>data(){ return{ list:{1:{type:'xx'}, 2:{type:'jj'}} }}
9. Asynchronous components (multiple) I think lazy loading refers to routing
-
import() function
-
On demand loading, asynchronous loading, when to use and when to load large components
// Normally import nexttick from '/ NextTick. Vue '/ / import normal components: {nexttick, slotdemo} / / import nexttick: () = > Import ('.. / necttick. Vue ')
10,keep-alive
- Cache components (product details page, product list page) (tab switching can use keep alive)
- Frequent switching does not require repeated rendering (frequent switching will destroy rendering and waste resources). You can use keep alive package
- Vue performance optimization
11,mixin
- Multiple components have the same logic and can be extracted
- mixin is not a perfect solution, there are problems
- The source of variables is not clear, which is not conducive to reading
- Naming is easy to repeat and conflict
Vue communication mode
-
props/$emit
Parent component A passes the value to child component B through props, and B passes the value to A through $emit
-
e m i t / emit/ emit/on
Trigger event and listen event
var Event = new Vue()Event.$emit(Event name, data)Event.$on(Event name, data => {})
-
Vuex
It is the state manager of vue. The stored data is responsive and will not be saved. It needs to be matched with localStorage
-
a t t r s / attrs/ attrs/listenners
vuex is usually used to transfer data by nested multi-level components, but it only transfers data without intermediate processing. vuex is a little overqualified and can be used - $attrs/$listeners.
a t t r s : package contain father do use field in no cover p r o p place knowledge other of special nature Bind set , through too v − b i n d = " attrs: contains the attribute binding in the parent scope that is not recognized by prop, via v-bind=“ Attrs: contains attribute bindings in the parent scope that are not recognized by prop, and is passed into internal components through v − bind = "attrs"
l i s t e n e r s : package contain Yes father do use field in of v − o n matter piece prison hear implement , through too v − o n = " Listeners: contains the v-on event listeners in the parent scope=“ Listeners: contains the v − on event listeners in the parent scope through v − on = "listeners"
-
provide/inject
Ancestor components provide variables through provide, and child components inject variables through inject. provide/inject mainly solves the communication problem between cross domain components
A. Vue provides the name variable to all its subcomponents through provide: name. B.vue injects the name variable through inject, which can be used through this Name accesses the variable, but it is not responsive. The value in A.vue changes, and the value in B does not change
-
p a r e n t / parent/ parent/children and ref
ref: if it is used on ordinary DOM elements, the reference points to DOM elements, and the reference on sub components points to component instances
$parent / $children: access parent-child instances
Unable to cross levels or between brothers
1, Wechat applet
1. Basic grammar usage
- After it is declared in data, the {}} mastauch syntax is required for use in the page, which is different from vue: src = "data" sec = "{data}}"
Routing principle
How to set the route
Sub route, lazy load route guard
How is the routing mode set
The difference between hash mode and history
When to use hash and when to use history
The difference between computed and watch
es6 syntax: update: function() {} === update() {}