Home > Web Front-end > JS Tutorial > body text

Vue underlying principles and component communication

php中世界最好的语言
Release: 2018-06-15 14:16:08
Original
2316 people have browsed it

This time I will bring you the communication between the underlying principles of Vue and components. What are the precautions for communicating between the underlying principles of Vue and components? The following is a practical case, let’s take a look.

The underlying principle of vue?

Communication between vue components?

How many methods are there to determine the data type in JS?

The most common method to determine: typeof

Method to determine the type of a known object: instanceof

Judge based on the constructor of the object: constructor

The invincible and omnipotent method: jquery.type()

What is the difference between vue and angular?

1.vue is just the view layer in mvvm. It is just a tool library like jquery, not a framework, while angular is the mvvm framework.
2.Vue’s two-way bonding is based on 3.getter/setter in ES5, while angular implements its own set of template compilation rules, which requires so-called "dirty" checking, while vue does not. . Therefore, Vue is more efficient in performance, but at the cost of not being supported by browsers below IE9.
4.vue needs to provide an el object for instantiation, and all subsequent scopes are also under the el object, while angular is the entire html page. A page can have multiple Vue instances, but Angular doesn't seem to work this way.
5.vue is really easy to get started and the learning cost is relatively low. However, there is not a lot of information for reference. The official documents are relatively simple and lack comprehensive use cases. For advanced usage, you need to study the source code yourself, at least for now.

Tell me about your understanding of angular dirty checking?

In angular you can't tell whether your data has changed, so it sets some conditions. When you trigger these conditions, it performs a detection to traverse all the data. , compare the changes you made, and then execute the changes.
This inspection is very unscientific. And the efficiency is not high, there are a lot of redundant places, so it is officially called dirty check.

active-class is a property of which component?

The router-link component of the vue-router module.

How to define nested routing?

In actual projects, we will encounter multiple layers of nested components, but how do we implement nested routing? Therefore, we need to use the children configuration in the parameters of VueRouter, so that route nesting can be implemented well.

index.html, there is only one routing exit

<p id="app"> 
  <!-- router-view 路由出口, 路由匹配到的组件将渲染在这里 --> 
  <router-view></router-view> 
</p>
Copy after login

main.js, the redirection of the routing will display the home component as soon as the page is loaded, because of the redirection Points to the home component, and the redirect point must be consistent with the path point. There are sub-routes inside children. Of course, sub-routes can also be nested inside sub-routes.

import Vue from 'vue' 
import VueRouter from 'vue-router' 
Vue.use(VueRouter) 
//引入两个组件 
import home from "./home.vue" 
import game from "./game.vue" 
//定义路由 
const routes = [ 
  { path: "/", redirect: "/home" },//重定向,指向了home组件 
  { 
    path: "/home", component: home, 
    children: [ 
      { path: "/home/game", component: game } 
    ] 
  } 
] 
//创建路由实例 
const router = new VueRouter({routes}) 
new Vue({ 
  el: '#app', 
  data: { 
  }, 
  methods: { 
  }, 
  router 
})
Copy after login

home.vue, click Show to display the sub-route. The exit of the sub-route must be in the parent route, otherwise the sub-route cannot be displayed.

<template> 
  <p> 
    <h3>首页</h3> 
    <router-link to="/home/game"> 
      <button>显示<tton> 
    </router-link> 
    <router-view></router-view> 
  </p> 
</template>
Copy after login

game.vue

 <template> 
  <h3>游戏</h3> 
</template>
Copy after login

How to define dynamic routing of vue-router? How to get the passed dynamic parameters?

In the index.js file in the router directory, add /:id to the path attribute.

Use the params.id of the router object.

What kind of navigation hooks does vue-router have?

Three types,

The first one is the global navigation hook: router.beforeEach(to,from,next), its function is to judge and intercept before jumping.
Second type: Hooks within components
Third type: Separate routing of exclusive components

What is scss? What are the installation and usage steps in vue.cli? What are its major features?

Pre-compilation of css.

Usage steps:

The first step: Use npm to download three loaders (sass-loader, css-loader, node-sass)

Step 2: Find webpack.base.config.js in the build directory, and add an extension.scss to the extends attribute

Step 3: Still in the same file, configure one module attribute

Step 4: Then add the lang attribute to the style tag of the component, for example: lang="scss"

What are the major features:

1. You can use variables, such as ($ variable name = value);
2. You can use mixers, such as ()
3. You can nest

What is mint-ui? how to use? Name at least three ways to use components?

Vue-based front-end component library. npm installation, then import styles and js, vue.use (mintUi) is introduced globally. Introduced locally in a single component: import {Toast} from ‘mint-ui’.

Component one: Toast (‘login successful’);
Component two: mint-header;
Component three: mint-swiper

What is v-model? how to use? How to bind events to tags in Vue?

Can realize two-way binding, instructions (v-class, v-for, v-if, v-show, v-on). The data attribute of vue's model layer. Binding event:

What are the advantages and disadvantages of iframe?

iframe is also called an embedded frame. An embedded frame is similar to a frame web page. It can embed the frame and content of a web page into an existing web page.

Advantages:

Solve the loading problem of slow-loading third-party content such as icons and advertisements

Security sandbox

Parallel loading script

Easy to make navigation bar

Disadvantages:

iframe will block the Onload event of the main page

Even if the content is empty, loading will take time

No Semantics

Briefly describe Sass and Less, and explain the difference?

They are dynamic style languages, CSS preprocessors, and an abstraction layer on CSS. They are compiled into CSS using a special syntax/language.

The variable symbols are different, less is @, and Sass is $;

Sass supports conditional statements, you can use if{}else{}, for{} loops, etc. Less does not support it;

Sass is based on Ruby and is processed on the server side, while Less needs to introduce less.js to process the Less code and output Css to the browser

What is axios ? how to use? Describe the process of using it to implement login functionality?

Module that requests background resources. npm install axios -S is installed, and then sent across domains, which needs to be set in the configuration file config/index.js. If the background is Tp5, define a resource route. Use import in js, and then .get or .post. If it succeeds, it will be returned in the .then function, if it fails, it will be returned in the .catch function.

axios tp5 advanced, what is the operation of calling axios.post('api/user')? What about axios.put(‘api/user/8′)?

Cross-domain, add user operations, update operations.

What is vuex? how to use? Which functional scenario uses it?

State management in the vue framework. Introduce store into main.js and inject it. A new directory store is created,...export. Scenarios include: status between components in a single-page application. Music playback, login status, add to shopping cart

What is the mvvm framework? What is the difference between it and other frameworks (jquery)? Which scenarios are suitable?

A model view viewModel framework, data model model, viewModel connects two

Difference: vue data-driven, display the view layer through data instead of node operations.

Scenario: Scenarios with a lot of data operations, more convenient

What are the methods for customizing instructions (v-check, v-focus)? What hook functions does it have? What are the other hook function parameters?

Globally defined instructions: There are two parameters in the directive method of the vue object, one is the instruction name, and the other is the function. Instructions defined in the component: directives

Hook functions: bind (triggered by binding event), inserted (triggered when node is inserted), update (related updates within the component)

Hook function parameters: el , binding

Name at least 4 types of instructions in vue and their usage?

v-if: Determine whether to hide; v-for: Loop out the data; v-bind:class: Bind an attribute; v-model: Implement two-way binding

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

vue is used to write a routing plug-in. router-link, router-view

#What are the navigation hooks? What parameters do they have?

Navigation hooks are:

a/Global hooks and hooks exclusive to components. b/beforeRouteEnter, afterEnter, beforeRouterUpdate, beforeRouteLeave

Parameters:

There are to (the route to go), from (the route to leave), next (this function must be used to go to the next A route, if not used, intercept it) The most commonly used ones are these

What is the principle of Vue's two-way data binding?

vue.js uses data hijacking combined with the publisher-subscriber model to hijack the setters and getters of each property through Object.defineProperty(), and publish messages when the data changes. To the subscriber, trigger the corresponding listening callback.

Specific steps:

Step 1: Recursively traverse the data objects that need to be observed, including the attributes of the sub-attribute objects, and add them Setter and getter
In this case, assigning a value to this object will trigger the setter, and then you can monitor the data changes

Second step: compile parses the template instruction and converts the variables in the template Replace it with data, then initialize the rendering page view, bind the update function to the node corresponding to each instruction, and add subscribers to monitor the data. Once the data changes, receive a notification and update the view

Step 3 : Watcher subscribers are the bridge of communication between Observer and Compile. The main things they do are:
1. Add themselves to the property subscriber (dep) when they are instantiated.
2. They must have an update. () Method
3. When notified by dep.notice() of attribute changes, you can call your own update() method and trigger the callback bound in Compile, then you will be done.

Step 4: MVVM serves as the entrance to data binding, integrates Observer, Compile and Watcher, uses Observer to monitor changes in its own model data, uses Compile to parse and compile template instructions, and finally uses Watcher to set up The communication bridge between Observer and Compile achieves the two-way binding effect of data changes -> view updates; view interactive changes (input) -> data model changes.

Please explain in detail your understanding of the vue life cycle?

A total of 8 stages are divided into before/after creation, before/after loading, before/after update, before/after destruction

Before/after creation: In the beforeCreated stage, the mounting element $el and data object data of the vue instance are both undefined and have not been initialized. In the created phase, the data object data of the vue instance is available, but $el is not.

Before/after loading: In the beforeMount stage, $el and data of the vue instance are initialized, but the virtual dom node before is still mounted, and data.message has not been replaced. In the mounted phase, the vue instance is mounted and data.message is successfully rendered.

Before/after update: When data changes, the beforeUpdate and updated methods will be triggered.

Before/after destruction: After executing the destroy method, changes to the data will no longer trigger the periodic function, indicating that the Vue instance has released event monitoring and binding to the dom, but the dom structure still exists.

Please tell me the process of encapsulating vue components?

First of all, components can improve the development efficiency of the entire project. It can abstract the page into multiple relatively independent modules, which solves the problems of our traditional project development: low efficiency, difficult maintenance, reusability and other problems.

Then, use the Vue.extend method to create a component, and then use the Vue.component method to register the component. Child components require data and can accept definitions in props. After the child component modifies the data, it wants to pass the data to the parent component. You can use the emit method.

How do you know vuex?

vuex can be understood as a development model or framework. For example, PHP has thinkphp, java has spring, etc.
Centrally manage changes in driver components through status (data source) (such as spring's IOC container centrally managing beans).

Application-level status is concentrated in the store; the way to change the status is to submit mutations, which is a synchronous thing; asynchronous logic should be encapsulated in actions.

What is vue-loader? What are the uses for using it?

A loader that parses .vue files and converts template/js/style into js modules.

Purpose: js can be written in es6, style can be scss or less, template can be added with jade, etc.

Please tell me the usage of each folder and file in the src directory in the vue.cli project?

The assets folder is for static resources; components is for components; router is for defining routing-related configurations; view; app.vue is an application main component; main.js is the entry file

vue. How to use custom components in cli? Have you encountered any problems?

Step one: Create your component file (smithButton.vue) in the components directory. The script must export default {

Step two: Import it into the page (component) you need to use :import smithButton from '../components/smithButton.vue'

Step 3: Inject it into the components property of the subcomponent of vue, components:{smithButton}

Step 4: Used in the template view,
The problem is: naming smithButton, when using it, it is smith-button.

Talk about your understanding of Vue.js template compilation?

In short, it is converted into an AST tree first, and then the obtained render function returns VNode (Vue's virtual DOM node)

Detailed steps:

First, the template is compiled into an AST syntax tree (abstract syntax tree, which is a tree representation of the abstract syntax structure of the source code) through the compile compiler. compile is the return value of createCompiler, which is used to create the compiler. In addition, compile is also responsible for merging options.

Then, the AST will get the render function through generate (the process of converting the AST syntax tree into a render function string). The return value of render is VNode. VNode is the virtual DOM node of Vue, which contains (label name , child nodes, text, etc.)

vue’s history

history How many steps forward or backward in the record

What is the difference between vuejs, angularjs and react?

1. Differences from AngularJS

Similar points:

both support instructions: built-in instructions and custom instructions.

Both supports filters: built-in filters and custom filters.

all support two-way data binding.

does not support low-end browsers.

Differences:

1. AngularJS has a high learning cost, such as the addition of the Dependency Injection feature, while the APIs provided by Vue.js itself are relatively simple and intuitive.

2. In terms of performance, AngularJS relies on dirty checking of data, so the more Watchers, the slower it becomes.

Vue.js uses observation based on dependency tracking and uses asynchronous queue updates. All data is triggered independently.

For huge applications, this optimization difference is quite obvious.

2. Differences from React

Similar points:

React uses special JSX syntax, and Vue.js also recommends writing .vue special file format in component development. There are some conventions on file content, and both need to be compiled before use.

The central idea is the same: everything is a component, and component instances can be nested.

all provide reasonable hook functions, allowing developers to customize their needs.

does not have built-in column number AJAX, Route and other functions into the core package, but is loaded as a plug-in.

Supports the features of mixins in component development.

Difference:

React relies on Virtual DOM, while Vue.js uses DOM templates. The Virtual DOM used by React will perform dirty checks on the rendered results.

Vue.js provides instructions, filters, etc. in the template, which can operate the DOM very conveniently and quickly.

vue life cycle interview questions

What is the vue life cycle?

The process from creation to destruction of a Vue instance is the life cycle. That is, a series of processes from starting to create, initializing data, compiling templates, mounting Dom → rendering, updating → rendering, uninstalling, etc. We call this the life cycle of Vue.

What is the role of vue life cycle?

There are multiple event hooks in its life cycle, making it easier for us to form good logic when controlling the process of the entire Vue instance.

How many stages are there in the vue life cycle?

It can be divided into 8 stages in total: before/after creation, before/after loading, before/after update, before/after destruction

Which hooks will be triggered on the first page load?

The beforeCreate, created, beforeMount, mounted hooks will be triggered when the page is loaded for the first time

In which cycle is DOM rendering completed?

DOM rendering has been completed in mounted

Briefly describe which scenarios are suitable for each cycle?

Some ways to use life cycle hooks: beforecreate: You can add a loading event here, which is triggered when the instance is loaded created: The event when the initialization is completed is written here, such as ending here loading event, asynchronous requests are also suitable to call mounted here: mount the element and get the DOM node updated: if the data is processed uniformly, write the corresponding function here beforeDestroy: you can make a confirmation box to confirm the stop event nextTick: after updating the data Immediately operate dom

arguments is a pseudo array, there is no traversal interface, and cannot be traversed

What are the differences between cancas and SVG

SVG

SVG is a language that uses XML to describe 2D graphics.
SVG is based on XML, which means every element in the SVG DOM is available. You can attach a JavaScript event handler to an element.
In SVG, each drawn graphic is considered an object. If the properties of an SVG object change, the browser can automatically reproduce the graphic.

Canvas

Canvas uses JavaScript to draw 2D graphics.
Canvas is rendered pixel by pixel.
In canvas, once a graphic is drawn, it will no longer receive the browser's attention. If its position changes, the entire scene needs to be redrawn, including any objects that may have been covered by graphics.

Comparison of Canvas and SVG

Canvas

Depends on resolution
Does not support event handlers
Weak text rendering capabilities
Ability to save the resulting image in .png or .jpg format
Best for graphics-intensive games where many objects will be redrawn frequently

SVG

Not dependent on resolution
Supports event handlers
Best suited for applications with large rendering areas (such as Google Maps)
High complexity will slow down rendering (any application that uses the DOM excessively will Unhappy)
Not suitable for game applications

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How nodejs mysql operates the database

How to use webpack vue environment LAN

The above is the detailed content of Vue underlying principles and component communication. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template