As one of the top three front-end frameworks, VUE is an essential skill for front-end developers. So how to systematically learn and master VUE? To this end, I have made a simple summary of the knowledge system system, the shortcomings of the big guys please forgive and correct, if you like can point a small praise!

Related to recommend

JS Basic summary (1) – data types
JS Basic Summary (2) – prototype and prototype chain
JS Basics (3) – scope and closure
This refers to call/apply/bind
EventLoopd is the implementation mechanism for JAVASCRIPT

What are the pros and cons of Vue

Advantages:

  1. Low coupling. Views can be changed and modified independently of the Model. A ViewModel can be bound to different views. When the View changes, the Model can not change, and when the Model changes, the View can not change.
  2. Reusability. You can put some view logic in a ViewModel and have many views reuse that view logic.
  3. Independent development. Developers can focus on business logic and data development (viewModels), designers can focus on page design, and Expression Blend makes it easy to design interfaces and generate XML code.
  4. Can be tested. Interfaces are harder to test, and tests can now be written against the ViewModel.
  5. Vue is a single-page application that refreshes the page locally, eliminating the need to request all data and DOM every time you jump to a page, which greatly speeds up access and improves the user experience. And its third-party UI library saves a lot of development time

Disadvantages: not conducive to SEO, community maintenance is not strong, compared to not mature enough

Vue common commands

  • v-html / v-text: Renders the label in the value
  • v-model: placed on form elements to implement two-way data binding
  • v-bind(abbreviated:) : used to bind inline properties
  • v-if / v-showThe value can be displayed if the value is true or false
  • v-cloak: Need to work with CSS: Solve the mustache display problem
  • v-onceThe corresponding label is rendered only once
  • v-for: Loops to display elements
  • v-onevent

Event modifier

Vue.js provides event modifiers for V-Ons, which are represented by an instruction suffix beginning with a dot.

  • stop: Prevents the event from spreading
  • prevent: Prevents the event default behavior
  • capture: Use event capture mode when adding event listeners
  • self: Triggers event handlers only when the current element fires
  • once: The event is triggered only once
  • passive: tells the browser that you do not want to block the event’s default behavior, and cannot be used with.prevent.
<! -- Prevent the click event from propagating -->
<a v-on:click.stop="toDo"></a>

<! Submit events no longer reload the page -->
<form v-on:submit.prevent="toSubmit"></form>

<! -- modifiers can be concatenated -->
<a v-on:click.stop.prevent="toDo"></a>

<! -- only modifiers -->
<form v-on:submit.prevent></form>

<! Add event listener with event capture mode
<! Events triggered by an inner element are processed here before they are processed by the inner element.
<div v-on:click.capture="toDo">.</div>

<! Trigger handler only if event.target is the current element itself -->
<div v-on:click.self="toDo">.</div>

<! Click event will only trigger once -->
<a v-on:click.once="toDo"></a>

<! -- The default behavior of the scroll event (i.e. the scroll behavior) will be triggered immediately -->
<div v-on:scroll.passive="onScroll">.</div>
Copy the code

Form modifier

  • .lazy Updates the view only after the cursor has left the input box
  • . Trim Filters the starting and ending Spaces
  • .number If you enter a number first, it limits the number you can enter. If you enter a string first, you don’t add the.number

Filter filter

Filter is to display the data to do further filtering processing, and then display, it is worth noting that the filter does not change the original data, just on the basis of the original data to generate new data.

  1. Define filter global registry
Vue.filter('myFilter'.function (value1[,value2,...] ) {
// Code logic
})
Copy the code

Local registration

new Vue({
 filters: {
    'myFilter': function (value1[,value2,...] ) {
       // Code logic}}})Copy the code
  1. Use filters
<! -- In double braces -->
<div>{{ message | myFilter }}</div>

<!-- 在 `v-bind` 中 -->
<div v-bind:id="message | myFilter"></div>
Copy the code

Computed attribute computed

Depending on other attribute values, and computed values are cached. Only when the dependent attribute values change, the computed value will be recalculated the next time the computed value is obtained.

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>

<script>
  var vm = new Vue({
    el: '#example'.data: {
      message: 'Hello'
    },
    computed: {
      // Calculates the getter for the property
      reversedMessage: function() {
        // 'this' points to the VM instance
        return this.message.split(' ').reverse().join(' ')}}})</script>
Copy the code

Listening property Watch

Observe and respond to data changes on Vue instances. Similar to listening callbacks for some data, each time the listening data changes, the callback is executed for subsequent operations. It can take three arguments

  • handler: the value is a callback function. That is, the function that should be executed when changes are heard
  • deep: the value is true or false; Make sure you’re listening in.
  • immediate: its value is true or false to verify that handler’s function is executed with the current initial value
watch:{
  message: {handler:function(val, oldVal){
      console.log(val, oldVal)
    },
    deep: true.immediate: true}}Copy the code

The difference between computed and Watch

  • computed: computes attributes and depends on other attributes, and computed values are cached. Only when the dependent attribute values change, the computed values will be recalculated the next time it obtains computed values.
  • watch: is more of a “watch” function, similar to some listening callbacks for data, which are executed for subsequent operations whenever the listening data changes.

Using the scenario

  • When we need to do numerical calculations and rely on other data, we should use computed, because we can take advantage of the caching nature of computed and avoid recalculating each time we get a value.
  • Watch should be used when we need to perform asynchronous or expensive operations when data changes. Using the Watch option allows us to perform asynchronous operations (accessing an API), limits how often we perform that operation, and sets the intermediate state until we get the final result. These are all things you can’t do with computed properties.

Life cycle function

  • beforeCreateVue instance mount element $EL and data object data are undefined and uninitialized
  • createdData is initialized, el is not initialized
  • beforeMount(before loading) The vue instance’s $EL and data are initialized and the associated render function is called for the first time
  • mounted(After loading) Ajax interaction during this process
  • beforeUpdate(Before update)
  • updated(Updated)
  • beforeDestroy(Before destruction)
  • destroyed(After destruction)

What is the order in which Vue’s parent and child lifecycle hooks are executed?

  1. Mouted/mouted/mouted/mouted/mouted/mouted/mouted/mouted/mouted/mouted
  • Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent Mounted
  1. Sub-component update process:
  • Affects the parent component: Parent beforeUpdate-> child beforeUpdate-> Child updated -> Parent updTED
  • Does not affect parent component: child beforeUpdate -> Child updated
  1. Parent component update process:
  • Affects child components: Parent beforeUpdate-> child beforeUpdate-> Child updated -> Parent updTED
  • Does not affect child components: parent beforeUpdate -> Parent updated
  1. Destruction process:
  • Parent beforeDestroy -> Child beforeDestroy -> Child destroyed -> Parent destroyed

The component registration

Components are one of the most powerful features of vue.js. Components extend HTML elements and encapsulate reusable code. The process of using a component includes the process of defining and registering it.

  1. Define the components
// Method one vue.extend
var MyComponent = Vue.extend({
  template: '
      
A custom component!
'
}) // Method 2: Create a.vue file Copy the code
  1. Certified components
// Global registration
Vue.component('my-component', MyComponent)

// Local registration
new Vue({
  el: '#app'.components: {
    'my-component': MyComponent
  }
})
Copy the code
  1. Using the component
<div id="example">
  <my-component></my-component>
</div>
Copy the code

Components by value

1. The parent component passes values to its child components

The props value can be an array or object;

// Array: not recommended
props: []/ / object
props: {inpVal: {type:Number.// The incoming value qualifies the type
  / / the type value can be a String, Number, Boolean, Array, Object, the Date, the Function, the Symbol
  // Type can also be a custom constructor and checked by instanceof
  required: true.// Whether to upload
  default:200.// default, object or array default values must be obtained from a factory function such as default:()=>[]
  validator:(value) {
    This value must match one of the following strings
    return ['success'.'warning'.'danger'].indexOf(value) ! = = -1}}}Copy the code

2. The $emit child component passes values to the parent component

Triggering a child triggers an event bound to it by the parent

/ / the parent component
<v-Header @title="title">
/ / child component
this.$emit('title', {title:'this is the title'})
Copy the code

3. Vuex data status management

  • state: Defines the repository to store data, which can be accessed through this.$store.state or mapState
  • getter: Gets the value of the store, considered a calculated property of the store, accessed through this.$store.getter or mapGetters
  • mutation: Changes the store value synchronously, which can be called via mapMutations
  • action: Asynchronously calls the function to perform mutation, thereby changing the store value, which can be accessed via this.$dispatch or mapActions
  • modules: module, if there are too many states, can be broken into modules, and finally at the entrance through… The introduction of deconstruction

4. Attrs and listeners

Attrs gets a value not defined in props in the child transmission parent

/ / the parent component
<home title="Here's the title." width="80" height="80" imgUrl="imgUrl"/>
/ / child component
mounted() {
  console.log(this.$attrs) / / {title: "this is the title", width: "80", height: "80", imgUrl: "imgUrl"}
}

// If the subcomponent defines props, the printed value is the properties of the cull definition
props: {
  width: {
    type: String.default: ' '}},mounted() {
  console.log(this.$attrs) //{title: "this is the title ", height: "80", imgUrl: "imgUrl"}
}
Copy the code

Listeners need to call methods of the parent component. Solution: Methods for parent components can be passed to internal components via V-on =” Listeners “– useful for creating higher-level components

/ / the parent component
<home @change="change"/>

/ / child component
mounted() {
  console.log(this.$listeners) // Get the change event
}
Copy the code

5. Dojo.provide and inject

Provide and Inject mainly provide use cases for high-level plug-in/component libraries. Direct use in application code is not recommended; And these options need to be used together; To allow an ancestor component to inject a dependency into all its descendants, no matter how deep the component hierarchy is, for as long as the upstream and downstream relationship is established.

// Parent component:
provide: { //provide is an object that provides a property or method
  foo: 'this is foo'.fooMethod:() = >{
    console.log('Parent component fooMethod is called')}},// Child or grandchild components
inject: ['foo'.'fooMethod'].// An array or object is injected into a child component
mounted() {
  this.fooMethod()
  console.log(this.foo)
}
// All child components under the parent component can utilize inject
Copy the code

6. $refs

Usually used for a parent component to call a child component

/ / the parent component
<home ref="child"/>

mounted(){
  console.log(this.$refs.child) // Get an instance of a subcomponent and manipulate data and methods directly
}
Copy the code

7. EventBus

  1. Declare a global Vue instance variable EventBus to store all communication data and event listeners.
  2. Similar to Vuex. 3. The principle is to use EMIT and instantiate a global VUE for data sharing
/ / in the main. Js
Vue.prototype.$eventBus = new Vue()

// Pass the value component
this.$eventBus.$emit('eventTarget'.'This is the value passed in from eventTarget.')

// Receive component
this.$eventBus.$on('eventTarget'.v= > {
  console.log('eventTarget', v) // This is the value passed by eventTarget
})
Copy the code

Configuring and using routes

  1. Configuring Routing Information
let routes = [
  {
    path: '/home'.component: home
  },
  {
    path: '/list'.component: list
  }
]

let router = new VueRouter({
  routes: routes
})
let vm = new Vue({
  el: '#app',
  router
})
Copy the code

Used in HTML

<div id="app">
   <router-link to='/home' active-class='current'>Home page</router-link>
   <router-link to='/list' tag='div'>The list of</router-link>
   <router-view></router-view>
</div>
Copy the code

In addition, vue-router can be configured with dynamic routes in the following ways

  • queryParameter transfer (question mark parameter transfer)
  • paramsParameter Transfer (Path parameter transfer)

Route lazy loading

There are 3 ways to implement route loading on demand (lazy route loading) in Vue project:

// 1. Vue asynchronous component technology:
{
	path: '/home'.name: 'Home'.component: resolve= > reqire(['the path path'], resolve)
}

// 2. Es6 proposal import()
const Home = () = > import('the path path')

// ensure()
{
	path: '/home'.name: 'Home'.component: r= > require.ensure([],() = >  r(require('the path path')), 'demo')}Copy the code

Routing guard

Vue-router provides navigation guards that are used to guard navigation by jumping or canceling. There are several opportunities for embedding route navigation: global, single route proprietary, or component level.

The global front-guard is often used to determine login status and verify menu permissions

router.beforeEach((to, from, next) = > {
  let isLogin = sessionStorage.getItem('isLogin') | |' '
  if(! isLogin && to.meta.auth) { next('/login')}else {
    next()
  }
})
Copy the code
  • to: Route: indicates the destination Route to be entered
  • from: Route: indicates the Route the current navigation is about to leave
  • nextThis method must be called to resolve the hook. The execution depends on the call parameters of the next method.

Guards within components

  • beforeRouteEnter
  • beforeRouteUpdate
  • beforeRouteLeave

Route cache Keepalive

Keep-alive is an abstract component provided by Vue. It is used to cache components to save performance. Since it is an abstract component, the V page will not be rendered as a DOM element after rendering.

<keep-alive>
  <router-view></router-view>
</keep-alive>
Copy the code

The lifecycle hook functions activated and deactivated are executed when a component is switched in keep-alive

1. 使用参数include/exclude

  • Include: string or regular expression. Only matching components are cached.
  • Exclude: indicates a string or regular expression. Any matching components will not be cached.
<keep-alive include="a,b">
  <router-view></router-view>
</keep-alive>
<keep-alive exclude="c">
  <router-view></router-view>
</keep-alive>
Copy the code

The include attribute indicates that only components whose names are a and B will be cached. Other components will not be cached. The exclude attribute indicates that all components will be cached except those whose name attribute is C.

2. Use the keepAlive attribute of $route.meta

You need to set the meta of the router in the router

export default new Router({
  routes: [{path: '/'.name: 'Hello'.component: Hello,
      meta: {
        keepAlive: false // No caching is required}}, {path: '/page1'.name: 'Page1'.component: Page1,
      meta: {
        keepAlive: true // Need to be cached}}}])Copy the code

Make a distinction between cached and uncached pages in app.vue

<div id="app">
  <router-view v-if=! "" $route.meta.keepAlive"></router-view>
  <keep-alive>
    <router-view v-if="$route.meta.keepAlive"></router-view>
  </keep-alive>
</div>
Copy the code

Hash and history modes

  • Hash mode: In the browser, the symbol “#” is called a hash, and the characters after # are read with window.location.hash. Features: Hash is in the URL, but is not included in the HTTP request. Hash is used to instruct browser actions. It is useless for server security and does not reload pages.

  • History mode: History uses new HTML5 features; Two new methods are provided: pushState(), replaceState() to modify the browser history stack, and popState events to listen for state changes.

  • In hash mode (http://localhost:8080#home), even if no configuration is required, the static server will always look for index.html and return it to us, and the Vue – Router will then take the character after # as an argument to transform the front page.

  • History pattern, what we want is: http://localhost:8080/home, but eventually return is index. The HTML, and then the vue – the router will get home as a parameter, to transform the front page. So who can do that in Nginx? The answer is try_files.

Recommend the article

Build a WebPack project from scratch
Summary of several webpack optimization methods
Summarize the methods of front-end performance optimization
Several common JS recursive algorithms
Build a VUE-CLI mobile TERMINAL H5 development template
Encapsulate a TOAST and Dialog component and publish it to NPM
This article covers front-end routing, back-end routing, single-page application, multi-page application
Discussion on JavaScript anti – shake and throttling