Summarize a series of knowledge points and frequent interview questions I use in learning VUE

Use:

npm install vue

Instructions:

v-text

v-html

v-if v-else-if v-else

v-show

V-if is true conditional rendering, inserting and removing nodes

V-show Regardless of the initial addition, the element will be rendered. Control the display of the element through the display property of CSS

V-bind Indicates the binding attribute

V-on binding event

V – a for loop

Key (used in conjunction with V-for) adds a unique identifier to the node, and DOM DIff can directly identify the node and efficiently update the UI

Mutation method: Data changes view updates automatically

Non-mutating approach: Data change views are not automatically updated

$set update

$set (target,key,value) forces view changes

Target: data source to change (can make an object or array)

Key: The specific data to be changed (arrays are subscripts and objects are corresponding key values)

Value: indicates the reassigned value

V – model:

Lazy You can add the lazy modifier to synchronize after the change event _

Number automatically converts the user’s input value to a numeric type

Trim Automatically filters the first and last whitespace entered by users

watch:

Listen for changes in data; Use scene Baidu translation, Baidu search

  • Depth listeners listen for values inside an object or array

computer:

Computed properties, which also listen for changes in data, listen for changes in dependent properties

You have to return the evaluated value of C

When the page refreshes, the first time I execute,

set get

Virtual DOm

Virtual Dom simulates nodes in the Dom through Object objects in JS, and then renders them to the real Dom through specific methods

Diff algorithm used

Why use the virtual DOM

Frequent dom manipulation can result in page redrawing and backflow, which should be reduced for performance optimization

Redraw only changes the style and does not cause the layout of the elements

Backflow: Causes the layout of elements

Life cycle:

A full life cycle of a Vue instance, starting from creation, initializing data, compiling templates, mounting dom, rendering – update – rendering, destroying, and so on

  • Create a period

1: Creates a VUE instance

2: Call the beforeCreate function

3: Initializes data and methods, placing the data attribute on the VUE instance

4: Call created (request data, start timer)

  • Mount the stage

1: Compiles the template to generate the virtual DOM

2: call beforeMount

3: Mount the virtual DOM to the real DOM

Mounted is invoked to request data.

  • Update period

1: Real-time monitoring of data changes

2: call beforeUpdate

3: The virtual DOM is re-rendered to the real DOM

4: Invokes updated

  • Destruction of period

1:vm.$destroy () is called

2: call beforeDestroy

3: Data backup

4: Call destroyed (clears animation and closes timer)

Modular:

Modularization: a JS file is a module, this module he realized what kind of function

Componentization: an object that contains HTML, CSS, and JS as a whole

Component registration

Global registration

Grammar:

Vue.component('Component name',{component configuration options})Copy the code

code

<body>
    <div id="main"> <! - 2 the calling component - > < mycon > < / mycon > < myfoot > < / myfoot > < mycon > < / mycon > < / div > < / body > < script > ponent (global components / / / / Vue.com'Component name',{component configuration options}) // 1: Define component Vue.component('mycon',{
    template:
      "
})


Vue.component("myfoot",{
    template:
      
bottom
}) var app=new Vue({ el:"#main", data:{ } }) </scriCopy the code

Local registration

Local components can only be used within their own VUE instance mount scope

Grammar:

var app=new Vue({
    el:"#main", data: {}, the methods: {}, watch: {}, computed: {}, components: {component name: {} configuration object, component name 2: {configuration object}}})Copy the code

code

    <div id="main"> <! - 2 the calling component - > < mycom > < / mycom > < com > < / com > < / div > < / body > < script > var app = new Vue ({el:"#main",
    data:{
    },
    methods:{},
    watch:{},
    computed:{},
    components:{
        mycom:{
            template:
      
Our class is versatile
}, com:{ template:"
Hua Hua loves singing and dancing
"
} } }) </script>Copy the code
  • Component naming conventions
    • Semantic as much as possible
    • Cannot be an existing HTML tag, (nav, header, footer, aside, section…..)
    • Not all caps
    • You can use a single tag when using a component (only the last one used).
  • A component’s template, template, can have only one root element

Data must be a function in a component

  • If the data is an object that js object types are stored in the object reference, if there are multiple components, can share data, leading to a component data change may cause another component change, if use a return object function, each using the component returns a new object, you won’t get the sharing of data

Components are nested

  • Globally registered components can be used by any component as a child component
<body>
    <div id="main">< con></con> </div> </body> <script> // extend creates a component constructor, not an instance, cannot be used in new Vue directly var com= vue. extend({template:"< div > < button > button < / button > < / div >"
})


var con=Vue.extend({
    template:`
      <div><a href="#"> link < / a > < big - com > < / big - com > < / div > `}) ponent (Vue.com'bigCom',com)


var app=new Vue({
    el:"#main",
    data:{
        
    },
    components:{
        con:con
    }
})
</scriptCopy the code
  • The component’s configuration option configures its child components again

grammar

New Vue(el:"#main", components:{component name :{template:
      
< component 1>
, components:{component name 1 :{template:"<div></div>",}}}})Copy the code

code

<body>
    <div id="main">      
         <con></con>  
    </div>
</body>
<script>
var app=new Vue({
    el:"#main", data: {}, components: {con: {template: ` < div > < button > switch < / button > child > < < / child > < / div > `, components:{ child:{ template:`<div><inputtype="text" /></div>`
                }
            }
        }
    }
})
</script>Copy the code

The contents of the template are isolated as templates

code

<body>
    <div id="main"> <con></con> </div> <! -- define a template with the template tag --> <template id="con-temp">< div> <button> Switch </button> <child></child> </div> </template> <template id="child-temp">
        <div>
            <hr/>
            <input type="text" />
        </div>
    </template>
</body>
<script>
var app=new Vue({
    el:"#main",
    data:{
        
    },
    components:{
        con:{
            template:"#con-temp",
            components:{
                child:{
                    template:"#child-temp"
                }
            }
        }
    }
})
</script>Copy the code

Dynamic components

use

<component is="Component name"></component>Copy the code
  • The IS attribute indicates the name of the component to render

# Component relationships

This.$children The current component or the children of the vue instance
​ mounted(){
This.$children[subscript]. Property retrieves data for the child component
​ }
This.$parent Is the parent of the current component

Component data communication

Father to son

1: When the parent component calls the child component, it assigns a custom attribute to the child component, and the custom attribute is passed to the root tag of the child component

The parent component

<child  message="In public"></child> // pass the value of the variable MSG to the child <child :message="msg" ></child>Copy the code
2: Subcomponents receive custom properties props:[‘ Property name 1’, ‘Property Name 2’] via the props property in the component configuration options.

Child components

 props:['message']Copy the code
3: Use this property directly
{{message}}Copy the code

Event modifier

Stop events from bubbling <a V-on :click.stop="doThis"></a> <! <form V-on :submit. Prevent ="onSubmit"></form> <! <a V-on :click.stop.prevent="doThat"></a> <! <form V-on :submit. Prevent ></form> <! -- Use event capture mode when adding event listeners --> <! <div V-on :click.capture= <div V-on :click.capture= <div v-on:click.capture="doThis">... </div> <! Trigger handler only if event.target is the current element itself --> <! <div v-on:click.self= <div v-on:click.self="doThat">... </div> <! <a V-on :click.once= <a v-on:click.once="doThis"></a> <! -- Call 'vm.submit()' only if 'key' is' Enter '--> < INPUT V-on :keyup.enter="subCopy the code

routing

1- Routing configuration – Routing is written as a separate module

Create the router.js file in the SRC directory

import Vue from 'vue'


import Index from './components/Index'
import Catgory from './components/Catgory'// 1: import -vue-router import VueRouter from'vue-router'Var routes=[{route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route: {route:'/',component:Index},
     {path:'/cat'Var router=new VueRouter({routes})exportImport the module router.js' 'js import router from in default router-main. js'./router.js'


new Vue({
  el: '#app'Router, // Inject the router instance into the vue instance each component can use this.$routeAnd this.$router
  components: { App },
  template: '<ApCopy the code
  • The router- Link component is rendered with an A tag. Clicking this tag will change the browser address bar
  • Every time the address bar of the browser changes, the matched components are displayed in the router-view based on routing rules

####2– Routing mode: mode

history
Hash (default, url with #)
Abstract url unchanged
// 4 Creating a route instance ----mode Route mode --historyhash(Default value, url contains#) abstract url unchanged
  var router=new VueRouter({routes,mode:"history"})Copy the code

3– Route nesting

In the project, the first-level navigation has the home page and the user page, and the second-level navigation has two pages of login and registration

  • 1: In the routing rules file, find the rule with secondary navigation
Var routes=[{path:'/',component:Index},
     {path:'/cat',component:Catgory},
     {path:'/cart',component:Cart},
     {path:'/mine',component:Mine,children:[
         {path:'/mine/login',component:Login},
         {path:'/mine/register',component:Register}
     ]}
  ]Copy the code
  • 2:Mine.vue components write router-link and router-view
<template>
    <div class="mine">
           <ul>
               <li><router-link to='/mine/login'</router-link></li> <li><router-link to='/mine/register'> register < / router - the link > < / li > < / ul > < the router - the view > < / router - the view > < / div > < / template >Copy the code

4– Programmatic navigation

Through JS code to achieve route jump

Add history to History

<router-link to="/"></router-link>


this.$router.push("/")
this.$router.push({path:'/'})Copy the code

History is not added to history

this.$router.replace('/mine/login')Copy the code

Advances and retreats in the historical record

this.$routerGo (1) this progress.$routerThe go (1) backCopy the code

5- Route redirection

When we access /a, we automatically jump to /b

```jsCopy the code

var routes=[

{path:’/a’,redirect:’/b’} ] “`

6- Named routes

Assign a name to a route rule. When a page is redirected, the route is redirected using the name

Routing rules

{path:'/home',name:'zy',component:Home},Copy the code

Page jump

<router-link :to="{name:'zy'}"> home page < / router - the link >Copy the code

####7- Dynamic routing

www.abc.com/news/103

1: Router.js is configured for the route

{path:'/detail/:id',component:Detail}Copy the code

2:router-link

<router-link to="/detail/5"></router-link>


<router-link :to="'/detail/'+item.id"></router-link>Copy the code

3: Get the id value passed (dynamic parameter)

this.$route.params.idCopy the code

####8- Routing parameters

www.abc.com/news?id=102…

1: routing rule

{path:'/detail',component:Detail},Copy the code

2:router-link

 <router-link :to='"/detail? id="+item.id'>
                {{item.title}}
 </router-link>Copy the code

3: gets the id value passed

this.$route.query.idCopy the code

: How do parameters pass between routes

<router-link :to="'/detail/'+item.id"></router-link> Receive: this.$route.params.id
<router-link :to='"/detail? id="+item.id'>{{item.title}}</router-link> Receive: this.$route.query.idCopy the code

$router = $route

Router stores methods such as this.$router. Push replace Go
$route.query, $route.query

Navigation guard

Vue-router provides navigation guards that are used to guard navigation by jumping or canceling

Global guard

Router. beforeEach((to,from,next)=>{// to---- where to go // from---- where to come from // console.log(from,"from")
  // console.log(to.path,"to") // next(); // Pass, // demand, when entering the shopping cart, to determine whether to login, login to the shopping cart, not login to jump to the login pageif(to.path=='/cart'){// make a decision whether to log inif(!localStorage.getItem("user")){
            console.log(123)
              next('/login'}}else{
        next()
      }
})Copy the code

Route exclusive guard

Find the routing rule file

 {path:'/cart',component:Cart,beforeEnter:(to,from,next)=>{
            //  console.log(to,"to");
            //  console.log(from,"from") // Just check whether you are logged inif(localStorage.getItem('user')){
              next()
            }else{
              next('/login')}}}Copy the code

Component internal guard

export default {
    data() {return {
         msg:"In the male it"}}, beforeRouteEnter(to,from,next){// Before entering the route // no! Can!!!! Console.log (this) next()}, beforeRouteUpdate(to,from,next){// Route updates console.log(to, from,next){// Route updates console.log(to,"to-update")
       this.msg="Guangzhou Campus"}, beforeRouteLeave(to,from,next){// Exit the route and execute console.log(to,"to-leave")
          next()
    }
}Copy the code

json-server

When developing tests locally, you can use jSON-server to simulate JSON data

Install the json-server command

npm install json-server -gCopy the code

Create a jsonServer directory and create a db.json file in the directory

{
  "userlist":[
       {
           "id": 1,"name":"Rustling"."age": 25."hobby":"Sing"
       },
       {
        "id": 2."name":"A lot"."age": 12."hobby":"Beating"}}]Copy the code

Command line execution suspends the service

json-server --watch --port 4000 db.jsonCopy the code

axios

Promise based HTTP library that can be used in browsers and Node.js

Using axios

Xios is mounted on the prototype of Vue

main.js


  import axios from 'axios'
  Vue.prototype.$axios= Axios uses this in each component.$axios.get(Copy the code

Install axios

npm install axios
or
yarn add axiosCopy the code

The AXIos GET request takes no arguments

// axios.get()"http://localhost:4000/userlist"(res) / /. Then = > {/ / console log (res) data) / /}) / / the second writing axios ({method:'get',
                url:'http://localhost:4000/userlist'
            })
            .then(res=>{
                console.log(res.data)
            })Copy the code

The AXIos GET request passes parameters

 axios.get('http://localhost:4000/newsArr/'+id) // second type axios.get('http://localhost:4000/newsArr',{
  params:{
    id:id
  }
})Copy the code

The AXIos delete deletes the data

axios.delete('http://localhost:4000/newsArr/'+id)
  .then(res=>{
      alert("Deleted successfully")})Copy the code

Axios’ POST adds data

//               axios({
            //     method: 'post',
            //     url: 'http://localhost:4000/newsArr'// data: {// title:this.title //} //)'http://localhost:4000/newsArr', {
                   title:this.title
                 })
                .then(res=>{
                    this.$router.push('/index/list')})Copy the code

Change to AXIos put

 axios.put('http://localhost:4000/newsArr/'+this.id,{
                title:this.userobj.title
            })
            .then(res=>{
               this.$router.push('/index/list')})Copy the code

Native JS ajax request five steps XMLHttpRequest

(1) Create an XMLHttpRequest object, that is, create an asynchronous call object.

(2) Create a new HTTP request and specify the HTTP request method, URL, and authentication information.

(3) Set the function that responds to the change of HTTP request status.

(4) Send HTTP requests.

(5) Get the data returned by the asynchronous call.

(6) Use JavaScript and DOM to achieve local refresh.

Var xmlHttp = new XMLHttpRequest();function CommentAll() {/ / the second step, the registered callback function xmlHttp. The onreadystatechange = callback1; / / {/ /if (xmlHttp.readyState == 4)
    //        if (xmlHttp.status == 200) {
    //            var responseText = xmlHttp.responseText;


    //        }
    //}
    //第三步,配置请求信息,open(),get
    //get请求下参数加在url后,.ashx?methodName = GetAllComment&str1=str1&str2=str2
    xmlHttp.open("post"."/ashx/myzhuye/Detail.ashx? methodName=GetAllComment".true); / / under the post request need to configure the request header information / / xmlHttp setRequestHeader ("Content-Type"."application/x-www-form-urlencoded"); // Step 4: Send the request. For the POST request, place the parameters to be passed in xmlhttp.send ("methodName = GetAllComment&str1=str1&str2=str2"); //} // Step 5, Function callback1() {if (xmlhttp.readyState == 4) if (xmlhttp.status == 200) {// Get the returned data xmlHttp.responseText; //json string to JSON format data = eval(data); $.each(data, function(i, v) { alert(v); }); Private void GetAllComment(HttpContext context) {//Params can get and post values. string methodName = context.Request.Params["methodName"]; //QueryString can only fetch values passed by get. string str1 = context.Request.Form["str1"]; String str2 = context.Request["str2"]; List
      
        comments = new List
       
        (); comments.Add(methodName); comments.Add(str1); comments.Add(str2); String commentsJson = new JavaScriptSerializer().serialize (comments); string commentsJson = new JavaScriptSerializer(). context.Response.Write(commentsJ
       
      Copy the code

Webpack sets up the cross-domain proxy

Root directory – > config – > index, js

proxyTable: {
      '/api': {
        target: 'http://47.106.12.223:8569'// changeOrigin:true, // Cross-domain pathRewrite: {'^/api': ' '// Override interface}}}Copy the code

Vue access/API is actually cross domain to http://47.106.12.223:8569

this.$axios.get('/api/getIndexData')Copy the code

Non-parent components pass values

Eventbus

#### implementation code

main.js

var eventbus=new Vue(); Prototype public area for storing data.$bus=eventbus;Copy the code

Coma.vue (Transfer value)

this.$bus.$emit('Event name'."Parameters")Copy the code

Comb.vue (received value)

this.$bus.$on('Event name',(val)=>{
  
})Copy the code

Separate EventBus from main.js

Create the eventbus.js file

import Vue from 'vue'var eventbus=new Vue(); Prototype public area for storing data.$bus=eventbus;Copy the code

Introduced in the main. Js

import './eventbus'Copy the code

Vuex status management

Vuex is a mechanism to implement global state management of components and facilitate data sharing among components

1: Benefits of using VUEX through managing state

  • Centrally manage shared data in VUEX for easy development and maintenance
  • Efficient realization of data sharing between components, improve development efficiency
  • The data stored in VUEX is responsive, keeping it in sync with the page in real time

2: Basic use of VUEX

The installation

npm install vue  --saveCopy the code

Import vuex package

import Vuex from 'vuex'Vuex.use (Vuex) // 2 Create store object const store=new vuex.store ({}) // 3 Exportexport default storCopy the code

Introduced in the main. Js

import store from './store/index.js'


new Vue({
  el: '#app'Router: {App}, template: {router: {store, router: {store, router: {store}, //'<App/>'
})Copy the code

state

Provide a single common data source and store all shared data in the store state

The first way to access data in state in a component

this.$store.state. The global data nameCopy the code

A second way to access data in state in a component

1 Import the mapState function import {mapState} from the VUEX as required'vuex'2 Use the mapState function to map global data required by the current component to computed property of the current component computed:{... mapState(['arr'.'str'])}Copy the code

mutation

Mutation is used to change data in the store

  • Store data can only be changed by mutation, but data in store cannot be manipulated directly
  • This is a slightly more cumbersome way to operate, but you can monitor all data changes centrally

Mutations define a function

new Vuex.Store({
  state:{num:1},
  mutations:{
    add(state){
       state.num++
    },
    addN(state,step){
      state.num+=step
    }
  }
})Copy the code
  • The component calls the mutations function
The first way:
this.$store.commit('add')Copy the code
D the second way
// 1 import mapMutations function import {mapMutations} from vuex'vuex'Methods :{// Map the function of mutations in store to the methods function of the current component through mapMutations... mapMutations(['add']} the view calls the Add side directlyCopy the code
  • The component calls the faraway function to pass arguments
The first way:
this.$store.commit('add'And 8)Copy the code
The second way
// 1 import mapMutations function import {mapMutations} from vuex'vuex'Methods :{// Map the function of mutations in store to the methods function of the current component through mapMutations... mapMutations(['add'.'addN'} the addN method < button@click = is called directly by the view"addN(7)">+N</buttonCopy the code

Use devTools

The three clicks in the top right corner of Chrome -> More Tools -> Extensions drag tools directly in

Actions are used to handle asynchronous tasks

Mutations are not available, but must be used for action if the data is changed by an asynchronous (complex business logic) operation, but mutations are also used to change the data indirectly within the action

The actions defined

Actions :{addAsync(context){//context contextsetTimeout(()=>{
              context.commit('add'},1000)}, addNAsync(context,step){//context contextsetTimeout(()=>{
                context.commit('addN',step)
             },1000)
        }
}Copy the code

Component triggers an action

The first way
// Trigger methods in actions without passing this.$store.dispatch('addAsync') // Pass the parameter this.$store.dispatch('addNAsync', 12Copy the code
The second way
import {mapActions} from 'vuex'methods:{ ... mapActions(['addAsync'.'addNAsync'])}Copy the code

getter

Getters are used to process data in a store to form new data

  • Getters are used to process the data in a Store to form new data similar to the computed properties of a VUE
  • As the data in the store changes, so does the data in the getter

Getters definition

getters:{
       shownum:state=>{
           return "The current latest quantity is ["+state.num +"】"}},Copy the code
The first way
this.$store. Getters. NameCopy the code
The second way
import {mapGetters} from 'vuex'computed:{ ... mapGetters(['shownum'])},Copy the code

The filter

Data is filtered during presentation, and the filtered data is displayed

define

Global definitions

Vue.filter('name'.function(v){
  return 'sss'; }, {{STR | name}}Copy the code
  • Local definition
new Vue({
  filters:{
    'Filter name':function() {return  ' '; }}})Copy the code

Filters can pass parameters

Vue.filter('name'.function(v,s){
  return '111'+s ; {{}) STR | name (The '%')}}Copy the code

Interview questions:

1. What is the difference between V-show and V-if?

V-show and V-if are both displayed when true and hidden when false

But when: false, v-show is used display:none; ,v-if adopts lazy loading (insert or delete nodes).

If you need to switch the display and hide frequently, run v-show

2. The difference between watch and computed?

Watch can only monitor data changes in data. Computed monitors changes that depend on data. Watch can perform asynchronous operations, but not computed. Perform the first time for watch when data changes, and perform the first time for computed page refresh

3. What is the function of the key value in vUE?

It is used in V-for to identify the uniqueness of components, better distinguish components, and update virtual DOM efficiently

4. Parent group communicates with child components?

Define a variable on the tag of the child component, the: variable = ‘passed value’, and accept the variable in the child using props

5. Child component communicates with parent component?

Write an event in the child component using this.$emit(‘ custom event name ‘, ‘data’); Receive with @custom event = ‘parent event’ on the child tag in the parent

6. Vue basic instruction?

V-model is mostly used for two-way data binding of form elements (same as Ng-Model in Angular)

V-for format: V-for =” field name in(of) array JSON “loop array or JSON (same as ng-repeat in Angular). Note that $index is removed starting with vue2

V-show displays content (same as ng-show in Angular)

V-hide Hides content (same as Ng-hide in Angular)

V-if show and hide (dom element deletion added as ng-if in Angular defaults to false)

V-else -if must be used with V-if

V-else must be used together with V-if. Do not use v-else alone. Otherwise, an error will be reported

V-bind dynamic binding function: to change the data on the page in time

V-on :click to bind a tag to a function, which can be abbreviated @, e.g. to bind a click function, the function must be written in methods

V-text parses text

V-html Parses HTML tags

{red:isred}’ {red:isred}’ {red:isred? red”:”blue”‘

Class: [‘a’,’b’]

7. What are the calculated attributes of vUE?

Putting too much logic into a template can make the template too heavy and difficult to maintain, so try to compute attributes in cases where complex processing of data is required and may be used multiple times.

Benefits: (1) the data processing structure is clear; (2) Rely on data, data update, processing results automatically update; ③ Inside the attribute this points to the VM instance; (4) When template is called, write the calculation attribute name directly. ⑤ Commonly used is getter method, get data, can also use the set method to change the data; (6) Compared with methods, methods recalculates regardless of the dependent data. However, when the dependent data does not change, computed data is obtained from the cache and does not recalculate.

8. What is the role of components in VUE? How are components defined and used?

Components are reusable Vue instances, and if a part of a web page needs to be used in multiple scenarios, it can be pulled out as a component for reuse. Components greatly increase code reuse rates.

There are two ways to define components:

(1) Global mode

Components created directly with Vue.component() are available to all Vue instances.

(2) Local mode

Trilogy 1. Create this component; 2. Register this component. 3. Use this component.

9. Dynamically bind class methods?

Object methods:

:class=”{ ‘active’: isActive }”

:class=”{‘active’:isActive==-1}”

or

:class=”{‘active’:isActive==index}”

Bind and judge multiple

:class=”{ ‘active’: isActive, ‘sort’: isSort }”

The second (in data)

:class=”classObject”

data() {

return {

classObject:{ active: true, sort:false }

}

}

Array methods

:class=”[isActive,isSort]”

data() {

return{

isActive:’active’,

isSort:’sort’

}

}

:class=”[isActive?’active’:”]”

:class=”[isActive==1?’active’:”]”

10. In what scenarios can VUE add in and out transition effects to any element or component?

Conditional rendering (using V-if);

Conditional presentation (using V-show);

Dynamic component;

Component root node

11. The advantages of VUE?

Low coupling. Views can be changed and modified independently of Model. A ViewModel can be bound to different “views”. The Model can remain unchanged when the View changes, and the View can remain unchanged when the Model changes.

Reusability. You can put some view logic in a ViewModel and have many views reuse that view logic.

Independent development. Developers can focus on business logic and data development (ViewModel), and designers can focus on page design.

Can be tested. Interfaces are harder to test, and tests can now be written against the ViewModel.

12. The use of deep monitoring?

watch:{

myObj:{

handler(newValue, oldValue) {

// Perform the operation

},

deep: true

}

}

13. Why is the component’s data not an object but a function?

The data in the component is written as a function, and the data is defined as the return value of the function. In this way, each time the component is reused, a new data is returned, similar to creating a private data space for each component instance and letting each component instance maintain its own data. However, simply writing in object form makes all component instances share a copy of data, which will cause a result that all changes will change.

14. Array changes cannot be detected in VUE. How to solve this problem?

(1)vm.arr.splice(index, 1, newValue)

(2)vm.$set(vm.arr, index, newValue)

(3)Vue.set(vm.arr, index, newValue)

15. Life cycle?

The lifecycle of a Vue instance is the process from creation to destruction. From creating, initializing data, compiling templates, mounting Dom, rendering, updating, rendering, destroying and so on,

Call it the lifecycle of Vue. The lifecycle can be beforeCreate created beforeMount Mounted beforeUpdate updated beforeDestroy destroyed

16. What are the common configuration options for vUE instances and what are they used for?

El Node to which it is mounted

The data of data

Methods of events

Computed properties

Watch the listener

Components Local components

Filters filter

Directives Specifies a self-defined directive

Lifecycle hook functions

17. How do I register a component?

Globally register Vue.com Ponent (‘ component name ‘,{configuration object})

Local registration:

components:{

Component name :{configuration object}

}

Note:

Component name Note the hump name pit, do not take HTML tag names;

Data is a function and must return an object

Template templates can have only one root tag and can be simplified by binding the template template inside the body with a selector

18. What is the core directive of the VUE form? What are form modifiers? What should I pay attention to?

Core instruction: V-model

Modifiers:.numer.lazy. Trim

Note: For radio functions, each input must have a value; For multiple selection, the binding is an array, and each input must have a value

19. What are the ways to pass parameters between pages in VUE and how to get values?

1. Search sends parameters

<router-link to=”/ address? Attribute name = Attribute Value “></router-link>

This $route. The query. The property name

2. Dynamic routing

Path :”/ address/variable name”

<router-link to=”/ address/data value “></router-link>

This $route. Params. Variable names

3. Local storage

setItem() getItem()

1. Understanding that VUE is an incremental framework?

Incremental means the least.

Vue may be worse than React or Angular in some ways, but it’s evolutionary and not compelling. You can implement a component or two on top of a larger system like jQuery. You can also use it for whole family development, when Angular uses it; You can also use its view with an entire lower layer of your own design. You can use the idea of OO and design patterns in the underlying data logic, you can use functional, you can use either, it’s just a lightweight view that does what it’s supposed to do, not what it shouldn’t do, and that’s it

Incremental means the least

Vue may not be as good as React or Angular in some ways, but it’s incremental and doesn’t insist. On large systems you can have one or two components implemented using Vue as jQuery, or you can develop the whole family using it and just do what it does.

2. Data transfer between non-parent and sibling components?

Var trans = new vue ()

$on(‘ event ‘, (n) =>{console.log(n)})

In component 2: trans.$emit(‘ event ‘, ‘sent data’) (written in event 2)

Var trans = new vue ()

Trans.$on(‘ event ‘, (n) =>{console.log(n)})

In component 2: trans.$emit(‘ event ‘, ‘sent data’)

3. Principle of two-way data binding of VUE

Object.defineproperty () is used to hijack the setter and getter of each attribute through object.defineProperty (). When the data changes, the message is published to the subscriber and the corresponding listener callback is triggered.

Use Object.defindeProperty () to hijack the setter() and getter() for each property and publish it to the subscriber when the data changes, triggering the corresponding listening callback

4. What is vue-router? What components does it have?

Router-view is a router plug-in with router-link and router-view components

Router plugins with router-link and router-view components

5. How to define a vue-router dynamic route? How to get the passed dynamic parameters?

Add /:id to the path attribute in the index.js file in the Router directory. ? Use the params.id of the Router object

In the index.js file in the Router directory. Add /:id.? To the path attribute. Use the params.id of the Router object

6. $router and $router?

$route is a routing information object, including route parameters such as’ Path, Hash, Query, fullPath, matched, name ‘.

$router is a route instance object, including route jump method, instance object, etc

$route is a routing information object, including ‘path, Hash, Query, fullPath,matched, name’ and other routing information parameters

$router is a route instance object, including route jump method, instance object, etc

7. How to use custom components in VUe-CLI? What problems have you encountered?

Create a vue file under Components

2. Introduce custom components in script tags where they are needed

Import component label name from ‘@/components/ component name ‘

Add component label names to Component

Create template template with component tag name </ component tag name >

Problem: Component names cannot be duplicated. Template can have only one root tag, and the component name must be the same as the referenced tag name

Create a vue file under Component

2. Introduce custom components in script tags where they are needed

Import component label name from ‘/components/ Component name

Add component label names to Component

3, Use component tag name < component tag name ></ component tag name > in template

: The component name must be unique. Only one template tag can exist. The component name must be the same as the referenced tag name

8. What is the use of each folder and file in the SRC directory in vue.cli project?

Assets: Store static files, such as CSS, JS, and image images

Components: Stores Components

Router: Stores routing files, including an inde.js routing file

App.vue: Main component page, used to display other components

Main.js: is an entry file used to import the required modules

Assets: Stores static files, such as CSS, JS, and image

Components: Stores Components

Router: Stores the routing file, which contains the index.js routing file

App.vue: Main component page, used to display other components

Main.js: is an entry file used to import the required modules

9. What is Axios? How to use it?

A module that requests background resources

Use NPM install axios -s to install

Import axios from {axios}

Attach axios to vue instance: vue.prototype.$axios = axios

Fill in Dev in index.js in config folder

ProxyTable: {

‘/ API: {

Target: ‘Target address of the proxy server’,

changeOrigin: true,

PathRewrite: {} “^ / API” : “”

}

}

Use this.$axios({this.$axios({

Url: ‘/ API/address’,

Method: ‘post’,// Post request must be set

Params:{parameter to pass}//post To set Params to data

}).then(res=>{}).catch(err=>{})

10. How to solve cross-domain problems when using AXIos in Vue?

Fill in Dev in index.js in config folder

ProxyTable: {

‘/ API: {

Target: ‘Target address of the proxy server’,

changeOrigin: true,

PathRewrite: {} “^ / API” : “”

}

}

11. Describe the advantages and disadvantages of single-page applications such as Vue.

Advantages: The goal of Vue is to implement data binding and composite view components for responses through as simple an API as possible, with a data binding system for responses at its core. MVVM, data-driven, componentized, lightweight, simple, efficient, fast, module-friendly.

Disadvantages: Does not support earlier versions of browsers, as low as IE9; Not conducive to SEO optimization (if you want to support SEO, it is recommended to render components through the server); The first time to load the home page is relatively long; You can’t use the browser’s navigation buttons. You need to move forward and backward.

Advantages: Vue aims to implement responsive data binding and composite view components through as simple an API as possible. The core is a responsive data binding system, MVVM, data-driven, componentized, lightweight, concise, efficient, fast, and module-friendly.

Disadvantages: Does not support earlier versions of the browser, the minimum support only IE9; Not conducive to SEO optimization (if SEO optimization is to be supported, it is recommended to use server-side rendering components); The first time to load the home page takes a little longer; You can’t use the browser’s navigation buttons.

12. What are the two cores of vue.js?

Data driven, component systems

Data-driven: ViewModel to ensure consistency between data and view.

Component systems: The application UI can be thought of as being entirely composed of component trees.

Data-driven: ViewModel to ensure consistency between data and view

Component systems: The application UI can be thought of as being entirely composed of components.

13. Briefly explain the role of the V-model directive in VUE.

The V-model directive is used to create two-way data binding on input, SELECT, text, checkbox, radio, and other form control elements. Automatically select the correct method to update the element based on the control type V-Model. It listens for user input events to update data

V – model instructions used in the input, select, text, checkbox, radio and so on form control elements to create a two-way data binding

The v-Model automatically selects the correct method to update the element based on the control type and listens for user input events to update the data

14. Which lifecycle hook functions are triggered by the first page load in Vue?

Generates beforeCreate, created, beforeMount, and Mounted

beforeCreate created beforeMount Mounted

15. What are the route guards?

Global guard beforeEach afterEach

Exclusive route guard beforeEnter

Component internal guard beforeRouteEnter beforeRouteUpdate beforeRouteLeave

Global guard beforeEach afterEach

Exclusive route guard beforeEnter

Component internal guard beforeRouteEnter beforeRouteUpdata beforeRouteLeave

16. What are the routing navigation hook functions in Vue? Briefly describe their parameters and functions.

Global navigation hook: router. BeforeEach ((to,from,next)=>{})// Intercept before jump

Router.afterEach((to,from,next)=>{})

Intraroute navigation: beforeEnter()

Intra-component navigation: beforeRouteEnter(); beforeRouteUpdate(); beforeRouteLeave()

To: target position; From: Current navigation is about to leave the route; Next (): must call, execute down

Global navigation hook: router. BeforeEach ((to,from,next)=>{})// Intercept before jump

Router.afterEach((to,from,next)=>{})

Intraroute navigation: beforeEnter()

Navigation within components: beforeRouteEnter(),beforeRouteUpdata(),beforeRouteLeave()

17. Explain how components transfer data in Vue?

1. Parent and child components

Define a variable on the tag of the child component, the: variable = ‘passed value’, and accept the variable in the child using props

2. Child and parent components

Write an event in the child component using this.$emit(‘ custom event name ‘, ‘data’); Receive with @custom event = ‘parent event’ on the child tag in the parent

3. Sibling components

Var trans = new vue ()

$on(‘ event ‘, (n) =>{console.log(n)})

In component 2: trans.$emit(‘ event ‘, ‘sent data’) (written in event 2)

18. How to use vue-Router?

Step 1: Import vue.js, then import vue-router.js, and vue-router need to be introduced after vue

<script src=”vue.js”></script>

<script src=”vue-router.js”></script>

Step 2: Set up the routing component

Let component configuration variable ={

The template: “# template id”,

data(){

return{}

}

.

}

Step 3: Establish the mapping

let routes = [

{

Path: “/ address”,

Component: Component configuration variable

},

{

Path :”/ address /: ID “, // Dynamic routing

Component: Component configuration variable

},

{

Path: “/ address”,

components:{

// <router-view name=”default”/>

<router-view name=” view name “/>

}

},

{

Path :”/ address “, // go back to address 2 when accessing address

Component: component configuration variable,

Redirect: “/ address 2”

},

{

Path: “/ address”,

Component: Component configuration variable A,

children:[

{

Path: “address 2”,

// Access/address/address 2

// The component configuration variables will be rendered in the router-view of the component configuration variable A template

Component: Component configuration variable

}

]

}

]

Step 4: Instantiate the routing object

let router = new VueRouter({

// routes:routes // routes

Routes,

linkActiveClass:”active”,

mode:”hash/history”

})

Step 5: Mount to the Vue instance

new Vue({

el:””,

data:{},

// router:router //

router

})

Step 6: Write router-view

<div id=”app”>

<router-view/>

</div>

Step 7: Use router-link to jump

<router-link to=”/ address “>

// Assign marks as appropriate

19. In Vue, which methods can be used to transfer parameters between pages and how to obtain values?

1. Search sends parameters

<router-link to=”/ address? Attribute name = Attribute Value “></router-link>

This $route. The query. The property name

2. Dynamic routing

Path :”/ address/variable name”

<router-link to=”/ address/data value “></router-link>

This $route. Params. Variable names

3. Local storage

setItem() getItem()

20. The underlying method of Axios?

Axios.get (request address, configure object). Then (res=>{res is the corresponding data})

Axios.post (request address, request data, configuration object). Then (res=>{… })

Axios.create (configure object)

Axios.all ([request 1, request 2]). Then (res=>{

Res is an array. The value of the array is the data information returned by each request

})

Axios ({configuration information})

1. What are the pros and cons of React?

Advantages: Componentized development,

Introduction of virtual DOM, good performance, fast response

JSX grammar,

Single item data binding

Cross-browser compatibility

Complete ecosphere and active community

Disadvantages:

An incomplete MVC framework

Not suitable for complex and large applications

2. What problem does React solve?

Componentization: The heart of React

Modularity: WebPack-based modular code can be written using Es6 or CommonJs

Development efficiency: The React code is basically a combination of components, with only one render function concerned, not view-specific changes

Efficiency: React implements the Virtual DOM, which is more efficient than the MVVM framework

Maintainability: React is based on flux or Redux architecture, and deterministic stores make it easy to locate problems

How does react DFF work?

With React, the render() function creates a react element tree at some point, and the render() function creates a DOM tree at the next state or props update. React compares the difference between the two trees. Calculate how to update the UI efficiently (update only the changes)

4. What is the purpose of the constructor call super(props)?

Subclasses cannot use this until super() is called, and in ES5 subclasses must call super() from constructor. The reason for passing props to super() is so that (in subclasses) constructor can access this.props

What does shouldComponentUpdate do?

Check whether shouldComponentUpdate

There are two states when a data change triggers the lifecycle function

Is there a shouldComponentUpdate function

The first one does not have normal data update

Three functions are fired:

To update ComponentWillUpdate render update componentDidUpdate

The second data is intercepted

Return true or false as desired. This function must return the relevant Boolean value, otherwise an error is reported

This function method takes two arguments, newProps and newState

ShouldComponentUpdate if true the order of the life cycle is shouldComponentUpdate whether componentWillUpdate will update the render componentDidUpdate update

If it’s false, we’re done

Just go shouldComponentUpdate whether to update

6. Why does virtual DOM improve efficiency?

React abstracts the DOM into a virtual DOM. The virtual DOM is actually an object to describe the DOM. By comparing the differences between the two objects, only the changed parts are rendered again to improve rendering efficiency. The DOM needs to be traversed when it changes and the native DOM traversable properties are 231 and most of them are not renderable updating pages is too expensive

7. Advantages of the arrow function?

Scope-safe: Before the arrow function, each newly created function defines its own this value (in constructors, new objects; In strict mode, this is undefined in function calls; If the function is called: object method, the base object and so on, but the arrow function does not, which uses the enclosing execution context this value.

Simplicity: Arrow functions are easy to read and write

Clear: When everything is an arrow function, any normal function can be immediately scoped with a definition, and the developer can always look up the next-higher function statement to see the value of this

8. What is a key in React? Why are they important?

What keys are help React keep track of which items have been changed, added, or removed from the list.

Each key is unique among its siblings. We have talked several times about the reconciliation process, and part of the reconciliation process is implementing a new element tree that is different from the previous one. Keys make dealing with lists more efficient, because React can use keys on child elements to quickly know if an element is new or was moved when comparing trees.

And not only does keys make the process more efficient, but without keys, React doesn’t know which local state corresponds to which item in motion. So when you map, don’t ignore keys.

9. In which lifecycle events does React make AJAX requests and why?

The AJAX request should be in the componentDidMount lifecycle event.

1. Fiber, the next implementation of React settlement algorithm, will have the ability to start and stop rendering on demand for performance advantage. One of the trade-offs is that componentWillMount, while starting AJAX requests in other lifecycle events will be “nondeterministic.” This means React can feel the need to start calling componentWillMount at different times. This is obviously a bad way to make AJAX requests.

2. You cannot guarantee that the AJAX request will not resolve before the component is mounted. If you do, that means you’ll try to set StState on an unmounted component, which not only won’t work, but will yell at you. Executing AJAX in componentDidMount guarantees that at least one component will be updated.

10. What are the advantages of using React?

It’s easy to see how a component is rendered just by looking at the Render function

2. The introduction of JSX makes component code more readable and makes it easier to understand the layout of components, or how components refer to each other

Support for server-side rendering, which improves SEO and performance

4. Easy to test

React only focuses on the View layer, so it can be used with any other framework (backbone. js, angular.js)

11. What is the difference between the component’s state and its properties?

State is a data structure for default values of data required when a component is mounted. States can mutate over time, but most of the time as a result of user event behavior.

Props(short for properties) is the configuration of the component. Props is passed from the parent component to its children, and is immutable as far as the children are concerned. A component cannot change its props, but it can group the props of its children together (unified management). Props isn’t just data either — callback functions can also be passed through Props.

12. What is JSX? How does the browser parse JSX?

JSX adds HTML syntax directly to JavaScript code, which is converted to pure JavaScript by a translator and executed by the browser. In real development, JSX has been compiled into pure JavaScript at the product packaging stage, with no side effects and making the code more intuitive and maintainable.

Browsers parse JSX by adding type=”text/bable” to script tags

13. What is the function of props in React?

React is a parameter that is passed to the component from outside. Because React is a one-way data flow, its main function is to transfer data from the parent component to the child component. It cannot be changed. Otherwise, the props and presentation of the subcomponent will not change. In addition to passing strings and numbers, props can pass objects, arrays, and even callbacks

14. What is the function of state in React?

State is used by components to save, control, and modify their state. It can only be initialized by constructor. State can be changed.

15. How to define class and function components in React? What’s the difference?

Function components:

import { React } from ‘react’

var App = (){

return()

}

Types of components:

import { React,Component } from ‘react’

class App extends Component{

render(){

return()

}

}

Function components have no state or lifecycle, so props is used to pass values

Class components have state and lifecycle, and pass values that require this.props

What are the React lifecycle hook functions?

Functions that fire when a component is loaded:

Constructor, componentWillMount, render, componentDidMount

Lifecycle functions that fire when component data is updated:

ShouldComponentUpdate, componentWillUpdate, Render, componentDidUpdate

Raised when the props pass is changed in the parent component:

componentWillReceiveProps

Triggered when a component is destroyed:

componentWillUnmount

17. What is ElementUi? How to use it in vUE project?

UI framework based on VUE2.0

React uses es5 and ES6 to bind buttons. What’s the difference?

es5:

<button onClick={this. function name}> <button onClick={this.

<button onClick={this. function name ()}>

Bind (this)}> <button onClick={this. bind(this)}>

es6:

<button onClick={()=>this. function name ()}>, es6 does not automatically execute functions, and can keep this pointing, much more than ES6.

19. In Vue, which methods can be used to pass parameters between pages and how can values be obtained?

1. Search sends parameters

<router-link to=”/ address? Attribute name = Attribute Value “></router-link>

This $route. The query. The property name

2. Dynamic routing

Path :”/ address/variable name”

<router-link to=”/ address/data value “></router-link>

This $route. Params. Variable names

3. Local storage

setItem() getItem()

20. What are the core concepts of VUEX and what do they mean?

A warehouse for unified management of data

State Shared data, similar to data

Getters processes the data of State without changing the original data, similar to computed data

Mutations modify the state data

Actions Trigger mutations to modify data (asynchronous)

Module manages data into modules (store is divided into multiple modules, each with its own state mutation Action getter)