A Vue.

1.1. Official documentation

Vue website

1). Front-end JS library developed by a Chinese ex-Google engineer (Yu Xi) 2). Features: * Follow MVVM mode * simple coding, small size, high efficiency, mobile /PC development * it only focuses on UI, can easily introduce vUE plug-in and other third library development projects 4). Vue includes a number of extensions (libraries): * VUe-CLI: Vue scaffolding * Vue-Resource (Axios): Ajax request * vue-router: routing * vuex: State management * Vue-lazyload: Image lazy loading * Vue-scroller: page sliding related * mint-UI: Ue-based component library (mobile) * Element-UI: Ue-based component library (PC) Basic Use: 1). Create vue instance object (VM), specify options (configuration) object EL: specify dom label container selector data: specify the object/function that initializes state data (returns an object) 3). Use {{}} or vue directives in the page templateCopy the code

1.2. Programming paradigm

Imperative programming => declarative programming

1.3. The Vue MVVM

View ViewModel(Vue) Model

  • View –> DOM layer, View, template page
  • ViewModel –> ViewModel (Vue instance), data binding and DOM listener
  • Model –> Model, data layer

1.4. Mustache

Mustache syntax: Supports variables as well as expressions

1.5. Options for Vue objects

1.51. el
The selector Vue that specifies the DOM tag container manages the corresponding tag and its child tagsCopy the code
1.52. The data
Object or function type Specifies the object that initializes the state of the attribute data. The VM also automatically owns all the attributes in data and can be accessed directly in the page. Using the data proxy: The VM object proxies operations (read/write) on all the attributes in data.Copy the code
1.53. The methods
The callback function has the event parameter by default, but can specify its own parameter. All methods are called by the vue object. To access properties in data, use this.xxx directlyCopy the code
1.54. The computed
The set/ GET method is used to compute and read the property data, while monitoring the change of the property data. How to define an object get/set properties are specified when creating the object: Get name () {return XXX} / set name (value) {} Object.defineproperty (obj, age, {get(){}, set(value){}}) instances are computed, including get and set methods (not commonly used). Calculated properties are cached and only called once if they are used more than once. (Watch monitors single, Cumputed monitors multiple)Copy the code
1.55. watch
XXX: function(value){} XXX: {deep: true, handler: fun(value)} vm.$watch('xxx', function(value){})Copy the code

1.6. Vue built-in instructions

Instruction API

Directives are special attributes prefixed with a V -. The value of the attribute directive is expected to be a single JavaScript expression (except for v-for), and the directive’s job is to react to the DOM’s consequences when the expression’s value changes.

V-text/V-html: specifies the tag body * V-text: treats it as plain text * V-html: parses value as an HTML tag to parse V -if v-elseV-show: show/hide elements * v-if: If Vlaue istrue, the current label will be output in the page * V -else-ifSaid: v -if"else ifBlock ". You can call it chained. * v-else: with v -ifIf value isfalse* V-show: adds the display style to the tag if vlaue istrue, display=block, otherwise none v-for: Traversal * Traversal number group: V -for="(person, index) in persons"* Traversal object: v-for="value in person"$key V-on: bind event listener * V-on: event name, which can be abbreviation: @ event name * Monitor specific key: @keyup.keycode @keyup.enter * Stop event bubble and prevent event default behavior: @click.stop@click. prevent * Implied object: $event V-bind: force binding parsing expression * HTML tag attributes do not support expressions, you can use v-bind * can be short: :id='name'
	* :class
	  * :class="a"
		* :class="{classA : isA, classB : isB}"
		* :class="[classA, classB]"
		* :class="classes()"
	* :style
		:style="{key(attribute name) : value(attribute value) "(prevents parsing into variables)}"V-model * Two-way data binding * Automatic collection of user input data * Principle V-bind, V-ON: Input * modifiers lazy,number,trim. Event.target. value V-slot * provides the named slot or the slot that needs to receive propref: Identifies a label * ref='xxx'* Read the label object:this.$refs. XXX v-once: * Elements and components are rendered only once and do not change as data changes. V-pre: * Skips compilation of this element and its children to show the original Mustache syntax. V -cloak: * [v-cloak] {display: none; } placeholderCopy the code

1.7. Custom instructions

1.71. Register office Directive
Vue.directive('my-directive'.function(el, binding){
  el.innerHTML = binding.value.toUpperCase() // Convert to uppercase
})
Copy the code
1.72. Register local directives
// Put it in the Vue instance
directives : {
  'my-directive' : function(el, binding) {
      el.innerHTML = binding.value.toUpperCase() // Convert to uppercase}}Copy the code
1.73. Use instructions
<div v-my-directive='xxx'>
Copy the code

1.8. Which methods in the array are reactive

  • Push () adds elements to the end of the array, which can be multiple
  • Pop () removes the last element in the array
  • Shift () removes the first element in the array
  • Unshift () adds elements to the front of the array, which can be multiple
  • Splice () deletes/inserts/replaces elements
  • sort()
  • reverse()
  • Changing an array by index cannot change the interface in response

1.9. Vue life cycle and responsive principle

1.91. Life cycle

Created ()/Mounted (): Starts asynchronous tasks (start timer, send Ajax request, bind listener) beforeDestroy(): does some finishing workCopy the code
1.92. Principle of responsiveness


2.0. Transition animation

Use vUE to manipulate CSS transition/animation template: use < Transition name='xxx'< span style = "box-sizing: border-box; color: RGB (51, 51, 51); line-height: 22px; font-size: 14px! Important; white-space: inherit! Important;" XXX - Enter,. XXX -leave-to: Specifies hidden style coding examples/* You can set different entry and exit animations */
	/* Sets the duration and animation function */
    .xxx-enter-active, .xxx-leave-active 
      transition: opacity .5s
    }
    .xxx-enter, .xxx-leave-to {
      opacity: 0
    }
    
    <button @click="isShow=! isShow">toggle</button>
    <transition name="xxx">
      <p v-if="show">hello</p>
    </transition>CSS animations are used in the same way as CSS, except that the v-Enter class name is not deleted immediately after the DOM is inserted, but when the AnimationEnd event is triggered. .bounce-enter-active {animation: bounce-in .5s;
}
.bounce-leave-active {
  animation: bounce-in .5s reverse;
}
@keyframes bounce-in {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.5);
  }
  100% {
    transform: scale(1); }}Copy the code

2.1. The filter

Filter (filterName, function(value[,arg1,arg2... ){return newValue}) 2). Using filters < div > {{myDate | filterName}} < / div > < div > {{myDate | filterName (arg)}} < / div >Copy the code

2.2. The plug-in

2.21. Custom plug-ins
/** Custom Vue plug-in */ 
(function () {
    const MyPlugin = {}
    MyPlugin.install = function (Vue, options) {
        // 1. Add a global method or attribute
        Vue.myGlobalMethod = function () {
            alert('Vue function object method execution ')}// 2. Add global resources
        Vue.directive('my-directive'.function (el, binding) {
            el.innerHTML = "MyPlugin my-directive " + binding.value })
        // 3. Add instance methods
        Vue.prototype.$myMethod = function () {
            alert('Vue instance object method execution')}}window.MyPlugin = MyPlugin
})()


Copy the code
2.22. Use plug-ins for pages
<div id="demo"> 
    <! -- Use custom instructions --> 
    <p v-my-directive="msg"></p> 
</div> 

<script type="text/javascript" src=".. /js/vue.js"></script> 
<script type="text/javascript" src="vue-myPlugin.js"></script> 
<script type="text/javascript"> 
    // Use custom plugins
    Vue.use(MyPlugin)
	let vm = new Vue({
        el: '#demo'.data: {
            msg: 'atguigu'}})// Call custom static methods
    Vue.myGlobalMethod() 
	// Call custom object methods
	vm.$myMethod() 
</script>
Copy the code

2.3. Data Broker (MvM.js)

1. Operations (read/write) on properties in another object through an object proxy 2. Through the VM object to proxy data object in all attributes of the operation 3. Benefits: more convenient operation of data in data 4. Basic implementation flow 1). Add attribute descriptors corresponding to attributes of data objects to vm via Object.defineProperty() 2). All added properties contain getters/setters 3). Inside the getter/setter to manipulate the corresponding property data in dataCopy the code

2.4. Template Parsing (compile.js)

1. Key object of template parsing: Compile object 2. Basic process of template parsing: 1). Remove all child nodes of el and add them to a new document fragment object. Parse all level child node recursion in fragment * parse expression text node * parse element node instruction attribute * parse event instruction * Parse general instruction 3). Textnode. textContent = value 1). /RegExp.$1 2). Retrieve the corresponding property value from data 3). Set the property value to textContent 4 of the text node. Incident command parsing: elementNode. AddEventListener (event name, the callback function. The bind (vm)) v - on: click = "test" 1). Retrieve event name from instruction name 2). Obtain corresponding event handler object from methods according to instruction value (expression) 3). Dom event listener that assigns the event name and callback function to the current element node binding 4). 5. General instruction parsing: elementNode.xxx = value 1). Get instruction name and instruction value (expression) 2). Get corresponding value from data according to expression 3). Use the instruction name to determine which attribute of the element node to operate on * V-text --textContent * V-html --innerHTML * V-class --className attribute 4). Set the value of the resulting expression to the corresponding attribute 5). Remove the element's directive attributeCopy the code

2.5. Data hijacking –> Data binding

Data binding (Model ==>View): 1). Once an attribute data in data is updated, all nodes on the interface that directly or indirectly use this attribute are updated (updated) 2. Data hijacking 1. Data hijacking is a technique used in VUE to implement data binding 2. Basic idea: Use defineProperty() to monitor all attribute (arbitrary level) data changes in data and update interface 3 when changes occur. 1). Observer * A constructor used to hijack all attributes of data * Redefines all attributes in data (get/set) * Creates a corresponding DEP object for each attribute in data 2) Each attribute (at all levels) in data corresponds to a deP object * when it was created: * The corresponding DEP object is created when each attribute in define Data is initialized * When an attribute value in data is set to a new object * the object structure {ID, // Each deP has a unique id subs // contains n arrays corresponding to the Watcher} * subs attribute description * When a Watcher is created, Internally, the current Watcher object is added to the subs of the corresponding DEP object * When the value of this data property changes, all watchers in the subs are notified of the update, Compile * The constructor of the object used to parse the template page (an instance) * The Compile object is used to parse the template page * A watcher object is created for each expression (non-event instruction) parsed. 4). Watcher * Each non-event directive or expression in the watcher template corresponds to a Watcher object * Monitors changes in the current expression data * when it is created: {vm, //vm exp, // the expression cb, // the callback function value when the corresponding expression data changes, DepIds = depIds; depIds = depIds; depIds = depIds; depIds = depIds; Conclusion: The relationship between DEP and Watcher: Man-to-many * A data attribute corresponds to a DEP, and a DEP may contain multiple Watcher (several expressions in the template use attributes) * a non-event expression in the template corresponds to a Watcher, There may be multiple DEPs in a watcher (several data attributes are included in the expression) * Data binding uses two core techniques * defineProperty() * Message subscription and publication 4. Bidirectional data binding 1). Bidirectional data binding is based on one-way data binding (Model ==>View) 2). Two-way data binding implementation flow: * Add input listener to current element while parsing V-model instruction * When the value of input changes, assign the latest value to the data property corresponding to the current expressionCopy the code

Two. Componentization

1.1. Component development

  • Provides an abstraction that allows us to develop individual reusable widgets to construct our applications.
  • Any application is abstracted into a tree of components.
1.11. Basic steps for registering components
  1. Create the component constructor vue.extend () method
  2. Vue.com Ponent ()
  3. Use components within the scope of the Vue instance
  <div id="app">
    <cpnc></cpnc>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    // 1. Create a component constructor object
    let cpn = Vue.extend({
      template: '
       
< H2 > Zs

History

}) // 2. Register components Vue.component('cpnc', cpn) const app = new Vue({ el: "#app".data: {}})
</script> Copy the code
1.12. Global components, local components
  <div id="app">
    <cpnc></cpnc>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    // 1. Create a component constructor object
    let cpn = Vue.extend({
      template: '
       
< H2 > Zs

History

}) // 2. Register component (global component) // Vue.component('cpnc', cpn) const app = new Vue({ el: "#app".data: { // Local components components: { // CPNC uses the component label name cpnc: cpn } } })
</script>// The data in the component is a function that returns an object to enhance reuseCopy the code
1.13. Parent, child component
1.14. Communication between parent and child components
  1. Pass data to subcomponents via props (when a humped prop is a feature, the property after V-bind: needs to be converted to message-prop.)
<! When passing data to child components as arrays and objects, the default value is function -->
<! -- Subcomponent -->
<template>
    <div id="container">
        {{msg}}
    </div>
</template>
<script>
export default {
  data() {
    return {};
  },
  props: {msg: String}};</script>
<style scoped>
#container{
    color: red;
    margin-top: 50px;
}
</style>


<! -- Parent component -->
<template>
    <div id="container">
        <input type="text" v-model="text" @change="dataChange">
        <Child :msg="text"></Child>
    </div>
</template>
<script>
import Child from "@/components/Child";
export default {
  data() {
    return {
      text: "Value of parent component"
    };
  },
  methods: {
    dataChange(data){
        this.msg = data
    }
  },
  components: {
    Child
  }
};
</script>
<style scoped>
</style>

Copy the code
  1. Send a message to the parent component via an event (this.$emit(” event name “), parameter)

    <! -- Subcomponent -->
    <template>
        <div id="container">
            <input type="text" v-model="msg">
            <button @click="setData">To the parent component</button>
        </div>
    </template>
    <script>
    export default {
      data() {
        return {
          msg: "Value passed to parent component"
        };
      },
      methods: {
        setData() {
          this.$emit("getData".this.msg); }}};</script>
    <style scoped>
    #container {
      color: red;
      margin-top: 50px;
    }
    </style>
    
    
    
    <! -- Parent component -->
    <template>
        <div id="container">
            <Child @getData="getData"></Child>
            <p>{{msg}}</p>
        </div>
    </template>
    <script>
    import Child from "@/components/Child";
    export default {
      data() {
        return {
          msg: "Parent Component Defaults"
        };
      },
      methods: {
        getData(data) {
          this.msg = data; }},components: {
        Child
      }
    };
    </script>
    <style scoped>
    </style>
    Copy the code
1.15. Access mode of parent and child components
  1. Parent accessing child: use children or children or children or refs(reference reference) (object type, default empty object, add ref attribute used)
  2. Child component accesses parent component $parent
1.16. Register component syntax sugar
// global component registration syntax sugar Vue.component('cpn1',{template: '<div> <h2> ZS </h2> <p> </p>}) const app = new Vue({el: "#app", data: {// Local component components: {/ / CPNC using the component tag name CPNC: {template: ` < div > < h2 > zs < / h2 > < p > history < / p > < / div > `}}}})Copy the code
1.17. Separate writing of template components
  1. The script tag must be of type TEXT/X-template
  2. The template tag
// separate the template<script type="text/x-template" id="cpn">
    <div>
      <h2>zs</h2>
      <p>history</p>
    </div>

  </script>	

  <template id="cpn">
    <div>
      <h2>zs</h2>
      <p>history</p>
    </div>
  </template>
  
  <script>
   const app = new Vue({
     el: "#app".data: {},
     components: {
       cpnc: {
         template: "#cpn"}}})</script>	
  
Copy the code

1.2. Advanced componentization

1.21. Slot

Slot makes packaged components more extensible

1.22. Named slot
<cpn>
   <h3 slot="button">Zhang SAN</h3>
</cpn>

<slot name="button"><button>button</button></slot>

Copy the code
1.23. Compilation scope
1.24. Scope slot

The parent component replaces the label of the slot, but the content is provided by the child component.

 <div id="app">
    <cpn>
      <div slot-scope ="slot">
        <span v-for="item in slot.data">{{item}}</span>
      </div>
    </cpn>
  </div>


  <template id="cpn">
    <div>
      <slot :data="num"></slot>
    </div>
  </template>

  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    const app = new Vue({

      el: "#app".data: {},
      components: {
        cpn: {
          template: "#cpn".data() {
            return {
              num: [1.2.3.4]}}}}})</script>
Copy the code

1.3. Modular development

1.31. Modular specification
The most basic encapsulation: inside an anonymous function, define an object. Add various properties and methods to an object that need to be exposed (without a direct definition of exposure). Finally, the object is returned and accepted outside using a MoudleA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- modular solve problems: 1. Module scope: Securely wraps the code of a module - without contaminating any code outside the module 2. Module uniqueness: uniquely identify a module - avoid repeated introduction 3. Module export: gracefully expose module API to external - do not add global variable 4. Introduction of modules: Easy to use to rely on the Module of the current modular solution 1.CommonJS -- node.js 2.AMD -- RequireJS 3.CMD -- SeaJS 4 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- CommonJS a separate JS file is a module, each module is a separate the require global functions are defined, the scope of the If the module introduced by require also contains dependencies, then load those dependencies in sequence. If importing the module fails, The require function should declare an exception module that exposes the API via the exports variable. Exports can only be an object, and the exposed API must be a property of this object. // a.exports. Foo = function() {console.log('foo')} //b.js var a = require('./a.js') a.foo() CommonJS Modules can only be used on the server (Node.js) and cannot be used directly in the browser. If the load will slow the blocking process -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ES6 Module basic usage Module / / variables, Module.js export var bar = 'bar' // function, module.js export function foo(){} Module.js var bar = 'bar' function foo(){} export {bar as myBar, foo} The module. Js function foo () {} export default foo -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ES6 module basic usage Reference module // Import specified object from module, support renaming, main.js import {foo, Bar as myBar} from './module.js' import myFoo from './module.js' // execute the module, Import * as myModule from './module.js' ES6 Module import is a reference to the original Module. <script SRC ="scripts/main.js" type="module"></script>Copy the code

3. Vue CLI

CLI: command-line Interface (CLI)

Vue CLI is an official release of Vue. Js project scaffolding.

Vue-cli can be used to quickly set up a VUE development environment and the corresponding Webpack configuration.

1.1. Install Vue scaffolding

NPM install -g@vue /cli # OR yarn global add @vue/cli NPM update -g@vue /cli # or YARN Global upgrade --latest @vue/cliCopy the code

Vue CLI >= 3 uses the same Vue command as the older version, so Vue CLI 2 (VUe-CLI) is overwritten. If you still need to use older versions of vue Init, you can install a bridge tool globally:

NPM install -g@vue /cli-init # 'Vue init' will run as' [email protected] '# CLI2 init webpack my-project # CLI3 initialize the project vue create my-projectCopy the code

1.2. Vue CLI2 details

1.21. Detailed description of directory structure

1.3. The runtime – only and runtime – the compiler

1.31 render and the template

1.32.VUE program running process

  • Runtime -compiler: template -> ast -> render -> vDOM -> UI
  • Runtime-only: render ->vdom -> UI

1.4 build and dev

1.5. Modify the configuration: alias webpack.base.conf.js

1.6. The Vue CLI3

  • Vue-cli 3 is based on Webpack 4, vue-CLI 2 is webapck 3
  • Vue-cli 3 design principle is “0 configuration”, remove the configuration file root directory, such as build and config
  • Vue – CLI 3 provides vue UI commands, which provide visual configuration and are more user-friendly
  • Remove static folder, add public folder, and move index.html to public
1.61. Project configuration

1.62. Detailed description of directory structure

1.63. Custom Configuration: Alias

4. Vue – the Router

Routing is the activity of transferring information from a source address to a destination address over an interconnected network

1.1. Back-end routing and front-end routing

  • Back-end rendering/back-end routing
  • Front end separation
  • SPA/ front-end routing

Back-end rendering: The server directly produces and renders the corresponding HTML pages and returns them to the client for display. For example: JSP pages

Front-end rendering: most of the content of the web page displayed in the browser is executed by the FRONT-END JS code in the browser, and the final rendering of the web page. (The back end returns JSON data, and the front end uses a pre-written HTML template to loop through the JSON data, concatenate strings, and insert pages.)

Back-end routing: When the browser switches between different urls in the address bar, each time it sends a request to the backend server, the server responds to the request, the server renders the entire page, and returns the page to the client.

Front-end routing: Core – Changes URL, but does not refresh the page as a whole.

1.2. The SPA page

SPA: Single page rich application, the entire web page has only one HTML page.

The most important feature of SPA is to add a layer of front-end routing on the basis of the separation of front and back ends.

The core of front-end routing is to change the URL, but not refresh the page as a whole.

1.3. The URL hash

The HASH of the URL, also known as the anchor point (#), essentially changes the href attribute of window.location.

We can change the href by assigning location.hash directly, but the page does not refresh.

Location. href "http://192.168.1.101:80/" location.hash = '/foo' "http://192.168.1.101:80/#/foo"Copy the code

1.4. HTML5 history mode

  • pushState
  • back
  • forward
  • replaceState
  • go
History. PushState ({}, ' ', '/ foo) location. The href "http://192.168.1.101:80/foo" is history. ReplaceState ({},' ', '/ foo') Location. The href "http://192.168.1.101:80/foo" "http://192.168.1.101:80/foo" is history. Go. (1) the location href "Http://192.168.1.101:80/" is history. The go (1) "http://192.168.1.101:80/foo"Copy the code

1.5. The Vue Router

Vue-router is based on routes and components

  • Routing is used to set access paths and map paths to components.
  • In a vue-Router single-page application, a change in the path of the page is a component switch.

1.6. Install and Use routes

Step 1: Import the route object and call vue.use (VueRouter) step 2: Create the route instance and pass in the route mapping configuration Step 3: import the route object and call vue.use (VueRouter) Import Vue from 'Vue' import VueRouter from 'vue-router' const Home = () => import('.. /components/Home.vue') const About = () => import('.. /components/About.vue') const Message = () => import('.. /components/Message.vue') const news = () => import('.. /components/news.vue') vue. use(VueRouter) The steps to use vue-router are as follows: Step 1: Create routing components step 2: Configure routing mapping: Component and path mapping Step 3: Use routing: <router-link> and <router-view> // define const routers = [{path: '/', redirect: '/home'}, {path: '/home', Component: Children: [{path: 'message', Component: message,}, {path: 'news', Component: news,}, {path: 'news', // Children: [{path: 'message', Component: message,}, {path: 'news', component: news,} '', redirect: 'message' } ] }, { path: '/about', component: }] // Create router instances const router = new VueRouter({routers, // Use HTML5 history mode for routers: 'history' // Change the default class name of the active-class attribute (router-link-active) LinkActiveClass: New vue ({el: '#app', router, render: H => h(APP)}) <router-link>: this tag is a component already built into vue-Router and will be rendered as a <a> tag. <router-view>: This tag will dynamically render different components based on the current path. The rest of the page, such as the title/navigation at the top, or some copyright information at the bottom, is at the same level as the <router-view>. During route switching, the components mounted by <router-view> are switched, and other contents remain unchanged.Copy the code

1.7. Other router-link attributes

  • To:, property: to, used to specify the jump path.
  • Tag: Tag can specify which component will be rendered later. For example, the code above will be rendered as one
  • Element, rather than
  • Replace: Replace does not leave a history, so if you specify replace, the back key will not return to the previous page
  • Active-class: When the route matches successfully, the system automatically sets a router-link-active class for the current element. If you set LinkActiveClass, you can change the default name.
    • This class is used when performing highlighted navigation menus or tabbars at the bottom.
    • The default router-link-active is used instead of modifying the class attributes.

1.8. Page route redirects

<button @click="linkToHome">Home page</button>

<script>
	export default {
        name: 'App'.methods: {
          linkToHome() {
              this.$router.push('/home')}}}</script>
Copy the code

1.9. Dynamic Routing

1.91. Types of Params
  • Set the route format to /router/: ID
  • How it is passed: Follow path with the corresponding value
  • The path is /router/123, /router/ ABC
{path: '/user/:userId', Component: User} < the router - link to = "/ User / 123" > User < / router - the link > < div > < h3 > {{$route. Params. UserId}} < / h3 > < / div > {{this.$route.params.userId}}Copy the code
1.92. Type of query
  • The route format is /router, which is the common configuration
  • Pass method: The object uses the Query key as the pass method
  • Route: /router? id=123, /router? id=abc
{{$route.params}} {{$route.query}}Copy the code
1.93. Two ways of passing parameters

Parameter transfer mode 1:


The second way to pass parameters: JavaScript code

1.94.
r o u t e and The route and
A router is different
  • Router is an instance of VueRouter. If you want to navigate to different urls, you use router as instance VueRouter. If you want to navigate to different urls, you use router.push

  • $route indicates the current router jump object, which can obtain name, path, query, and params

2.0. Lazy loading of routes

Function: Package the component corresponding to the route into a js code block, only when the route is accessed, load the corresponding component.

A: Const Home = resolve => {require.ensure(['../components/ home.vue '], () => { resolve(require('.. /components/Home.vue')) })}; Const About => require(['../components/ about.vue '], resolve); Const Home = () => import('.. /components/Home.vue')Copy the code

2.1. Nested routine by

2.2. Navigation Guard

website

  • Vue-router provides a navigational guard that listens for incoming and outgoing routes.
  • Vue-router provides beforeEach and afterEach hook functions that fire before and after a route is about to change.
We can define some headers in the hooks and use the meta to define them. We can also modify our headers using the navigation guard. '/home', Component: home, meta: {title: 'home'}}, {path: '/about', Component: about, title: 'about'}] const router = new VueRouter({routers,}) Router. BeforeEach ((to, from, next) => { window.document.title = to.meta.title; Next ()}) export default Router Navigation hook three parameters: to: destination route object to enter from: current navigation route object to leave next: call this method to enter the next hook.Copy the code

2.3 keep alive

Keep-alive is a component built into Vue that can preserve the state of contained components or avoid re-rendering.

  • Two attributes:
    1. Include-string or regular expression. Only matching components are cached
    2. Exclude – a string or regular expression. Any matching component will not be cached

Router-view is also a component. If it is wrapped directly in keep-alive, all view components matched by the path will be cached.

Verify this by declaring a periodic function by create.

2.4. TabBar case

  1. If you had a separate TabBar component underneath, how would you encapsulate it

    • Custom TabBar components for use in the APP
    • Put TabBar at the bottom and set the styles
  2. What is displayed in TabBar is determined by the outside world

    • Define the slot
    • Flex layout bisects the TabBar
  3. Custom TabBarItem that can pass in images and text

    • Define TabBarItem and define two slots: picture and text.
    • Wrap divs around the two slots to set styles.
    • Fill the slots to achieve the bottom TabBar effect
  4. Pass in the highlight image

    • Define another slot to insert active-icon data
    • Define a variable isActive, using v-show to determine whether to display the corresponding icon
  5. TabBarItem Binds routing data

    • Install route: NPM install vue-router -save
    • Complete the contents of router/index.js and create the corresponding component
    • Register the router in main.js
    • Add components to your APP
  6. Click item to jump to the corresponding route and dynamically determine isActive

    • Listen for item clicks and replace the routing path with this.$router.replace()
    • Through this $route. Path. IndexOf (enclosing the link). == -1 To check whether it is active
  7. Compute the active style dynamically

    • Encapsulate new compute properties: this.isactive? {‘color’: ‘red’} : {}

Code implementation

Five.Vuex

Vuex is a state management mode developed specifically for vue.js applications. Simply put, all variables that need to be shared by multiple components are stored in one object.

  • It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.
  • Vuex is also integrated into Vue’s official debugging tool, DevTools Extension, which provides advanced debugging functions such as zero-configuration time-travel debugging, status snapshot import and export, and so on.

1.1. Single-interface state management

1.2. Legend of Vuex Status Management

1.3. Vuex core Concepts:

  • State

    State Single State tree State: {count: 0}Copy the code
  • Getters

    /* Just like evaluating properties, the return value of a getter is cached based on its dependencies, and is recalculated only if its dependencies change. Getters cannot pass arguments by default. If you want to pass arguments, you have to make getters return another function */
    
    const store = new Vuex.Store({
      state: {
        todos: [{id: 1.text: '... '.done: true },
          { id: 2.text: '... '.done: false}},getters: {
        doneTodos: state= > {
          return state.todos.filter(todo= > todo.done)
        }
      }
    })
    Copy the code
  • Mutation

    The only way to update the store state of Vuex is to submit the Mutation. 2. A callback function (handler) whose first argument is state. Mutations are mutations. {increment(state){state-count ++}} increment(){this. code. store.mit ('increment')} When adding a new attribute to an object in state, update the data using the following method: Set (obj, 'newProp', 123) mode 2: The mind object reassigns the Mutation constant type to the old object -- the concept uses a constant to replace the type of the Mutation event. In general, the main reason not to do asynchronous mutation operations is because devTools can help us capture a snapshot of mutation when we use DevTools.Copy the code
  • Action

    /* Action is similar to Mutation, but is used instead of Mutation to perform asynchronous operations. In the Vue component, if we call the method in the action, we need to use dispatch, which also supports passing payload */
    
    mutations: {
      increment(state){state.count++}},actions: {
      increment(context,payload) {
        setTimeout(() = >{
          context.commit('increment', payload)
        }, 3000)}}Copy the code
  • Module

    /* Due to the use of a single state tree, all the application states are grouped into one large object. When the application becomes very complex, the Store object can become quite bloated. To solve these problems, Vuex allows us to split the Store into modules. Each module has its own state, mutation, action, getter, and even nested submodules -- split the same way from top to bottom: */
    const moduleA = {
      state: () = >({... }),mutations: {... },actions: {... },getters: {... }}const moduleB = {
      state: () = >({... }),mutations: {... },actions: {... }}const store = new Vuex.Store({
      modules: {
        a: moduleA,
        b: moduleB
      }
    })
    
    store.state.a // -> moduleA status
    store.state.b // -> moduleB status
    Copy the code

1.4. Project structure

├─ index.html ├─ download.js ├─ API │ ├─ ├─ ├─Extract THE API request├ ─ ─ components │ ├ ─ ─ App. Vue │ └ ─ ─... └ ─ ─ store ├ ─ ─ index. Js# where we assemble modules and export store├ ─ ─ actions. JsRoot level action├ ─ ─ mutations. JsMutation at the root level└ ─ ─ modules ├ ─ ─ cart. Js# Shopping cart module└ ─ ─ products. Js# Product module
Copy the code