Vue.js summary of detailed notes


The basic grammar

Interpolation expression
  1. V-cloak solves the problem of difference expression flickering

    <p v-cloak>{{msg}}</p>
    Copy the code
  2. Use the V-HTML directive to output HTML code:

    <div v-html = "message"></div>
    
    <script>
      const app = new Vue({
        el: '#app',
        data: {
          message:'<h1>Hello</h1>'
        }
      });
    </script>
    Copy the code
  3. By default, V-text does not flicker. It overwrites the original content of the element, but the interpolation replaces itself, not empties the entire element

    <h4 v-text="msg"></h4>
    Copy the code
  4. 14. v-bind: attribute binding mechanism

    <input type="button" value=" button" :click =" show">Copy the code
  5. V-on: The event binding mechanism, short for @, listens for DOM events

    <input type="button" value=" button" @:click =" show">Copy the code
    • In the event definition, the parentheses are omitted from the method, but the method itself needs an argument, so Vue passes the browser-produced event object as an argument to the method by default.
    • In call mode, use$eventTo manually get the browser parameters

Event modifier
<! <a :click.stop="doThis"></a> <! <form :submit. Prevent ="onSubmit"></form> <! - the modifier can series - > < a: click. Stop. Prevent = "doThat" > < / a > <! <form :submit. Prevent ></form> <! -- Use event capture mode when adding event listeners --> <! <div :click.capture="doThis"> <div :click.capture="doThis"> </div> <! Trigger handler only if event.target is the current element itself --> <! That event is not triggered from internal elements -- -- > < div: click the self = "doThat" >... </div>Copy the code

Dynamically bound style
<div id="app"> <! <h2 :style="{fontSize: size, backgroundColor: color}">{{message}}</h2> <! - the second binding approach - > < h2: style = "getStyle ()" > {{message}} < / h2 > < / div > < script > const app = new Vue ({el: '# app, data: { message: 'Hello', size: '50px', color: 'red' }, methods: { getStyle: function() { return {fontSize: this.size, backgroundColor: this.color} } } }); </script>Copy the code

V – for attribute
  1. Iterative array

    <ul>
        <li v-for = "(item , i) in sites">{{item.name}}</li>
    </ul>
    
    <script>
      const app = new Vue({
        el: '#app'.data: {
            sites:[
                { name: 'Runnoob'},
                { name:'Google'},
                { name:'Taobao'}}}]);</script>
    Copy the code
  2. Iterate over the properties of an object

    <div v-for = "(value ,key,index) in user">Values are: {{value}}-- key is: {{key}}-- index is: {{index}}</div>
    
    <script>
      const app = new Vue({
        el: '#app'.data: {
            user: {id:1.name:'guo'.gender:'nan'}}});</script>
    
    Copy the code
  3. The iteration number

    <p v-for = "I in 10"> <p v-for =" I in 10">Copy the code
    • When v-for iterates over numbers, the I value starts at 1
    • The key must be used when the key is usedV - the bind attributeIn the form of a binding that specifies the value of key

Difference between V-if and V-show
The characteristics of performance
v-for Each time the element is re-deleted or re-created High switching performance
v-show The DOM is not re-deleted and re-created each time High initial rendering cost

** If the element may never be visible to the user, v-if is recommended; If the element involves frequent switching, v-show is recommended


Two-way binding

Combined with radio type
<label for="male"> <label for="female"> <label for="female"> <label for="female"> <input type="radio" id="female" name="sex" value=" female" V-model ="sex"> female </label> <h2>{{sex}}</h2> <script> const app = new Vue({el: '#app', data: {sex: 'male'}}) </script>Copy the code

  • When writing data inside sex, due to bidirectional binding, the corresponding button will also be selected, which will solve the radio button default problem

Combine the Chechbox type
<label for="agree"> <input type="checkbox" ID =" Agree" V-model ="isAgree"> Agree agreement </label> < H2 >{{isAgree}}</h2> <button :disabled="! </button> <script> const app = new Vue({el: '#app', data: {isAgree: false) </script>Copy the code

<input type="checkbox" value=" basketball "V-model ="hobbies"> basketball <input type="checkbox" value=" table tennis" v-model="hobbies" Type ="checkbox" value=" hobbies" V-model ="hobbies"> hobbies ="hobbies" </h2> <script> const app = new Vue({el: '# app' data: {hobbies: [] / / marquee is corresponding to the array}}) < / script >Copy the code


Combine the SELECT type
<select name=" ABC "V-model ="fruit"> <option value=" apple "> apple </option> <option value=" banana "> banana </option> <option Value =" fruit "> </option> </select> <h2> <script> const app = new Vue({el: '#app', data: {fruit: 'banana'}}) </script>Copy the code

  • Note: The V-model of select is written in select!

Value binding

Values in values are defined as input values, but in real development, these input values may be defined in data, so you need to dynamically bind values to values by v-bind: value

<label v-for="item in allHobbies" :for="item"> <input type="checkbox" :id="item" :value="item" V-model ="hobbies">{{item}} </label> <h2> <script> const app = new Vue({el: '#app', data: {hobbies: [], allHobbies: [' basketball ', 'football', 'table tennis',' badminton]}}) < / script >Copy the code


Use modifiers
  1. Lazy modifier

    • By default, v-Model synchronizes input box data in real time
    • The lazy modifier allows data to be updated only when it loses focus or returns
    v-model.lazy = "message"
    Copy the code
  2. Number the modifier

    • By default, any letters or numbers entered in the input field are treated as strings
    • But if we want to deal with array types, it’s better to treat the content as a number
  3. Trim the modifier

    • If the input has a lot of content at the beginning and endThe blank space, you can use it to remove

Commonly used features

Custom instruction
  1. Global directives

    <div id="app"> <input type="text" v-focus> </div> <script> vue. directive('focus', { inserted(el) { el.focus(); } }) const app = new Vue({ el: '#app', data: { }, }); </script>Copy the code
    <div id="app"> <input type="text" V-color ='message'> </div> <script> vue. directive('color', {bind(el, El.style. backgroundColor = binding.value.color; } }) const app = new Vue({ el: '#app', data: { message: { color: 'blue' } } </script>Copy the code
  2. Local instructions

    <div id="app"> <input type="text" v-focus> </div> <script> const app = new Vue({ el: '#app', data: { message: { color: 'Blue'}}, // Local directives here add caching: {focus: {EL) {el.focus(); }}}}); </script>Copy the code

    For other instructions, please click: Vue Documentation – Custom instructions


Calculate attribute
<div id="app"> <h2>{{fullName}}</h2> </div> <script> const app = new Vue({ el: '#app', data: { firstName: 'Guo' lastName: 'shuaige'}, // Add computed: {fullName() {return this.firstName + this.lastname}}}) </script>Copy the code

The filter
  1. Function: Formats data, such as capitalizing a string, formatting a date to a specified format, etc.

  2. Global filters:

    // Enter a line of lowercase words, Capitalize the first letter to < div id = "app" > < input type = "text" v - model = "message" > < h2 > {{message | upper}} < / h2 > < / div > < script > Vue.filter('upper', function(val) { return val.charAt(0).toUpperCase() + val.slice(1); }) const app = new Vue({ el: '#app', data: { message: '' } }); </script>Copy the code
  3. Local filter:

    // Enter a line of lowercase words, Capitalize the first letter to < div id = "app" > < input type = "text" v - model = "message" > < h2 > {{message | upper}} < / h2 > < / div > < script > const app = New Vue({el: '#app', data: {message: ''}, // add filters here: { upper(val) { return val.charAt(0).toUpperCase() + val.slice(1); }}}); </script>Copy the code

The life cycle
  1. Vue instance generation process:


Array update detection
  1. Change method (modify original data)
The method name Corresponding purposes
push() Adds one or more elements to the end of the array and returns the new length
pop() Removes an element from the list (the last element by default) and returns the value of that element
shift() Removes the first element of the array and returns the value of the first element
unshift() Inserts its arguments into the arrayObject header, and moves the existing elements sequentially to the higher subscript to leave a gap
splice() Removes zero or more elements starting at index and replaces those deleted elements with one or more values declared in the argument list
sort() Sort the elements of an array
reverse() Reverses the order of the elements in an array
  1. Replace arrays (generate new arrays)
The method name Corresponding purposes
filter() Creates a new array of elements by checking all the elements in the specified array. It does not detect an empty array
concat() Join two or more arrays
slice() Returns the selected element from the existing array, including elements from start to end (not including the end)

We can receive the array after the method is called with a new array:

this.info = this.info.slice(0, 2);
Copy the code

Modify responsive data
  1. The first:

    Vue.set(app.items, indexOfltem, newValue)
    Copy the code
  2. The second:

    app.$set(app.items, indexOfltem, newValue)
    Copy the code

    Meaning of parameters:

    • Parameter one represents the name of the array to process
    • Parameter two represents the index of the array to be processed
    • Parameter three represents the value of the array to process

Componentized development

The basic use
  1. Global component registration:
Vue.component(component name, {data: component data, template: component template content})Copy the code
  • For example:
<div id="app"> <! <button-counter></button-counter> </div> <script> // vue.comPonent ('button-counter', { data() { return { count: 0 } }, template: ` < div > < button @ click = "count++" > click the {{count}} time < / button > < / div > `}) const app = new Vue ({el: '# app, data: {}}); </script>Copy the code
  1. Local component registration:
let ComponentA = {/*... */} let ComponentB = {/*... */} let ComponentC = {/*... */} new Vue({ el: '#app', components: { 'component-a': ComponentA, 'component-b': ComponentB, 'component-c': ComponentC, } })Copy the code
  • For example:
<div id="app">
    <hello-world></hello-world>
</div>
<script>
    let HelloWorld = {
      data() {
        return {
          msg: '123'
        }
      },
      template: '<div>{{msg}}</div>'
    }
    const app = new Vue({
      el: '#app',
      data: {},
      components: {
        'hello-world': HelloWorld
      }
    });
</script>
Copy the code

Note: A local component can only be used in the parent component that registers it


Data interaction between components
  1. Parent to child (static) : In a parent component, a value is passed directly to the child as a property; Child components are received via corresponding properties in props

  2. Parent to child (dynamic) : Values are entered inside the parent and received by the child via dynamically bound properties

    <div id="app"> <div>{{pmsg}}</div> <! Static -- -- - > < menu - item title = 'value from the parent components' > < / menu - item > <! -- dynamic --> <menu-item :title='ptitle'></menu-item> </div> <script> Vue.component('menu-item', {props: [' title '], the data () {return {MSG: 'child components of data itself'}}, the template: '< div > {{MSG + "-- -" + title}} < / div >'}); Const app = new Vue({el: '#app', data: {PMSG: 'parent ', ptitle:' dynamic binding '}}); </script>Copy the code
  3. Child component passes information to parent component:

    • Child components pass information to parent components through custom events

      <button @click='$emit("enlarge-text", 0.1)'>Copy the code
    • The parent component listens for events of the child component

      <menu-item @enlarge-text='fontSize += $event'></menu-item>
      Copy the code
  4. Non-parent components pass values

    • Separate event centers manage communication between components

      let eventHub = new Vue();
      Copy the code
    • Listen events and destroy events

      eventHub.$on('add-todo', addTodo);
      eventHub.$off('add-todo');
      Copy the code
    • Triggering event

      eventHub.$emit('add-todo', id);
      Copy the code

Dynamic components
  1. Use keep-alive on dynamic components

    // Select an article, switch to another TAB, and then switch back to the selected article instead of the default article. Use the <keep-alive> tag to wrap the dynamic component <keep-alive> <component V-bind :is="currentTabComponent"></component> </keep-alive>Copy the code

slot
  1. Basic usage

    <div > <script> vue.comonent ('alert-box', {template: vue.comonent ('alert-box', {template: ` <div> <strong>ERROR:</strong> <slot></slot> </div>` }); const app = new Vue({ el: '#app', data: { } }); </script>Copy the code
  2. A named slot

    < div id = "app" > < alert box - > < p slot = "header" > header information < / p > < p > content 1 < / p > < p > 2 content < / p > < p = "footer" > slot at the bottom of the information < / p > < / alert box - > < / div >  <script> Vue.component('alert-box', { template: ` <div> <header> <slot name="header"></slot> </header> <main> <slot></slot> </main> <footer> <slot name="footer"></slot>  </footer> </div>` }); const app = new Vue({ el: '#app', data: { } }); </script>Copy the code
  3. Scope slot

    • Application scenario: The parent component processes the content of the child component
    <div id="app">
        <cpn></cpn>
        <cpn>
          <template slot-scope="slot">
            <span v-for="item in slot.data">{{item}}--- </span>
          </template>
        </cpn>
    </div>
    
    <template id="cpn">
        <div>
          <slot :data="pLanguages">
            <ul>
              <li v-for="item in pLanguages">{{item}}</li>
            </ul>
          </slot>
        </div>
    </template>
    Copy the code

Front and back end interaction

Promise usage
Let p = new Promise(function(resolve, reject) {// call resolve() successfully; // reject(); }) //resolve and reject P.chen (function(ret) {// get normal result}), function(ret) {// get error message}Copy the code
  1. Commonly used API:

    • Instance methods

      • P. then() gets the correct result of the asynchronous task
      • P.catch () retrieves exception information
      • Of () will be executed either successfully or not
      queryData()
        .then(function(data) {
          console.log(data);
        })
        .catch(function(data) {
          console.log(data);
        })
        .finally(function() {
          console.log('finished');
        })
      Copy the code
    • Object methods

      • Promise.all() processes multiple asynchronous tasks concurrently, and results are obtained only when all tasks are completed
      • Promise.race() handles multiple asynchronous tasks concurrently, and as long as one task completes you get the result
      Promise.all([p1, p2, p3]).then((result) => {
        console.log(result);
      })
      Promise.race([p1, p2, p3]).then((result) => {
        console.log(result);
      })
      Copy the code

The fetch usage
fetch(url).then(fn2)
		  .then(fn3)
		  ...
		  .catch(fn)
Copy the code
  1. Request parameters – Common configuration options:

    • Method (String): HTTP request method. Default is GET(GET, POST, PUT, DELETE).
    • Body (String):HTTP request parameter
    • Headers (Object):HTTP request header, default {}
    fetch('/abc', { method: 'get' }).then(data => { return data.text(); }). Then (ret => {console.log(ret); })Copy the code
  2. Parameter passing in GET request mode

    // Fetch ('/ ABC? id=123').then(data => { return data.text(); }). Then (ret => {console.log(ret); }) / / the second way the fetch ('/ABC / 123, {method: 'get'}), then (data = > {return data. The text (); }). Then (ret => {console.log(ret); })Copy the code
  3. DELETE request-style parameter passing

    fetch('/abc/123', { method: 'delete' }).then(data => { return data.text(); }). Then (ret => {console.log(ret); })Copy the code
  4. Parameter passing in POST request mode

    fetch('/books', {
      method: 'post',
      body: 'uname=lisi&pwd=123',
      header: {
        'Content-Type': 'application/x-ww-form-urlencoded'
      }
    }).then(data => {
      return data.text();
    }).then(ret => {
      console.log(ret);
    })
    Copy the code
  5. PUT Parameter transfer in request mode

    fetch('/books/123', {
        method: 'put',
        body: JSON.stringify({
            uname: 'lisi',
            age: 12
        }),
        headers: {
        	'Content-Type': 'application/json'
        }
    }).then(data => {
        	return data.text();
        }).then(ret => {
            console.log(ret);
        })
    Copy the code
  6. Fetch response result

    • Text (): Treats the return body as a string
    • Json (): Returns the same result as json.parse (responseText)
    fetch('/abc' then(data => {
      return data.json();
    }).then(ret => {
      console.log(ret);
    })
    Copy the code

    Front-end engineering
    1. The basic syntax for ES6 modularity

      // Default export syntax export default Default export member // Default import syntax import receiver name from 'module identifier'Copy the code
    2. Note: export default can only be used once in each module, otherwise an error will be reported!

    3. Export on demand and import on demand

      Import {s1, s2 as ss2, } from './m1.js' export let s2 = 'CCC' export function say = function() {}Copy the code
    4. Import and execute the module code directly

      // The current file is m2.js for(let I = 0; i < 3; I ++) {console.log(I)} import the module code import './m2.js'Copy the code

    routing

    The basic concept
    1. Front-end routing: responsible for event monitoring, triggering events, through the event function render different content; It is essentially a correspondence between user events and event handlers

    2. Back-end routing: Returns different contents according to different USER URL requests

    3. Vue Router provides the following functions:

      • Support HTML5 historical mode or hash mode

      • Support nested routines by

      • Supported Routing parameters

      • Support for programmatic routing

      • Support named Routing


    Vue-router basic use

    Steps:

    • Step 1: Import the relevant library files
    <! --> <script SRC =".. /lib/vue-router.js"></script>Copy the code
    • Step 2: Add routing links

      • Router-link is a tag provided in VUE that is rendered as an A tag by default
      • The to attribute is rendered as an href attribute by default
      • The value of the to attribute is rendered as a hash address starting with # by default
      <router-link to="/user">User</router-link>
      <router-link to="/register">Register</router-link>
      Copy the code
    • Step 3: Add the route fill bit

      • Components that will be matched by routing rules will be rendered to the router-View location
      <router-view></router-view>
      Copy the code
    • Step 4: Define the routing components

      let User = {
        template: '<h1>User</h1>'
      }
      let Register = {
        template: '<h1>Register</h1>'
      }
      Copy the code
    • Step 5: Configure routing rules and create routing instances

      Const router = new VueRouter({// Routes: [// note: Component is an object, not a string {path: '/user', component: User}, { path: '/register', component: Register} ] })Copy the code
    • Step 6: Mount the route to the Vue root instance

      Const app = new Vue({el: '#app', router: router});Copy the code

    Route redirection

    Route redirection means that when A user accesses address A, he or she is forced to redirect to address C to display A specific component page. Using the redirect attribute, you can specify a new route address to easily configure route redirection

    Const router = new VueRouter ({routes: [/ / path according to the original address needs to be redirected, redirect to the new address {path: '/', redirect: '/ user'}, {path: '/user', component: User}, { path: '/register', component: Register} ] })Copy the code

    Vue-router Indicates the nested routine

    Usage steps: The steps for parent routing components are the same as the basic ones, and child routing components need to be defined in their parent routing components

    } let Tab2 = {template: '<h3>Tab1 child '} let Tab2 = {template: '<h3>Tab2 subcomponent '} const router = new VueRouter({routes: [// '/user'}, { path: '/user', component: User}, { path: '/register', component: Register, children: [ { path: '/register/tab1', component: Tab1}, { path: '/register/tab2', component: Tab2} ] } ] })Copy the code

    Vue-router Dynamically matches routes

    Application scenario: Routes are matched based on dynamic route parameters

    <router-link to="/user/1">User 1</router-link> <router-link to="/user/2">User 2</router-link> <router-link To ="/user/3"> user 3</router-link> let router = new VueRouter({routes: [// routes:] {path: '/user/:id', component: {$route.params.id}}</div>'}} User {{$route.params.id}}</div>'}Copy the code

    However, $route is highly coupled to the route and is not flexible enough, so you can use props to associate the component with the route

    • The value of props is of type Boolean:
    Const router = new VueRouter({routes: [//props if set to true, route.params will be set to component {path: '/user/:id', Component: User, props: true}]}) const User = {props: ['id'], // Use props to receive routing parameter template: '<div> id: {{id}}</div>'Copy the code
    • The value of props is of the object type:
    // Let User = {props: ['id', 'uname', 'age'], template: '< div > id is: {{id}} - name: {{uname}} - age: {{age}} < / div >'} const router = new VueRouter ({routes: [{path: '/user/:id', component: User, props: { uname: 'lisi', age: 18}} ] })Copy the code
    • The props value is of the function type:
    let User = { props: ['id', 'uname', 'age'], template: '< h1 > id is: {{id}} - name: {{uname}} - age: {{age}} < / h1 >'} const router = new VueRouter ({routes: [{path: '/user/:id', component: User, props: route => ({ uname: 'zhangsan', age: 19, id: route.params.id }) } ] })Copy the code

    After routing
    <router-link :to="{ name: 'user', params: {id: 3}}">User 3</router-link>
    
    const router = new VueRouter({
          routes: [
            { 
              name: 'user',
              path: '/user/:id',
              component: User, 
              props: route => ({
                uname: 'zhangsan',
                age: 19,
                id: route.params.id
              })
            }
          ]
        })
    Copy the code

    Vur-router programmatic navigation
    1. Common programmatic navigation apis:

      • This $router. Push (‘ hash address)
      • This.$router.go(n) this.$router.go(n
    2. Parameter rules for the router.push() method

      Router.push ({path: '/home'}) // Named router (pass parameters) Router.push ({name: '/user', params: {userId: 123}}) // with query parameters, become /register? uname=lisi router.push({ path: '/register', query: { uname: 'lisi' }})Copy the code
    3. Usage:

      </button> </div> const User = {template: '<div> <button @click="goRegister"> { goRegister() { this.$router.push('/register') } }Copy the code

    webpack

    The basic use

    Steps:

    • Run the command:

      npm install webpack webpack-cli -D
      Copy the code
    • Create a configuration file named webpack.config.js in the project root directory

    • In the webPack configuration file, initialize the following configuration:

      Module. exports = {mode: 'development' //mode specifies build mode}Copy the code
    • Under the scripts node of package.json, add dev script:

      "Scripts ": {"dev": "webpack" // scripts under the script node can be run by NPM run}Copy the code
    • Run the following code at the terminal to package the project:

      npm run dev
      Copy the code

    Webpack for other uses
    1. When webPack packages a file, it automatically recognizes whether it depends on other files and, if it does, processes that file automatically

    2. Webpack is mainly used to process js code written by users, and Webpack will automatically deal with the dependencies between JS, but in the development we not only have basic JS code processing, but also need to load CSS, images and so on, for Webpack itself, these transformations are not supported.

      The corresponding loader needs to be extended to Webpack

    3. Loader usage process:

      • Step 1: Install the Loader using NPM
      • Step 2: Configure the modules keyword in webpack.config.js
    4. Css-loader parses the CSS file, loads it using import, and returns the CSS code

      npm  install  --save-dev  css-loader
      Copy the code
    5. Style-loader adds the module’s export to the DOM as a style

      npm  install  style-loader  --save-dev
      Copy the code
    6. When WebPack packaged JS files, ES6 syntax was not converted to ES5, so that long meant that some browsers that didn’t support ES6 couldn’t run the program.

      If you want to convert ES6 syntax to ES5, you need to use Babel

      npm  install  --save-dev  babel-loader@  7bable-core  babel-preset-es2015
      Copy the code
    7. Webpack introduced vue. Js

      npm  install  vue  --save
      Copy the code
    8. Difference between EL and Template

      • In real development, if you don’t want to modify your Html template code, you can use the template attribute

        new Vue({
          el: '#app',
          template: `
            <div id="app">
              {{message}}
            </div>  
          `,
          data: {}
        })
        Copy the code
      • The code in the template property above can be substituted for the code in Html

        <div id="app">
            <h2>{{message}}</h2>
          </div>
        Copy the code
    9. Plugin stands for plug-in and is usually used to extend an existing architecture

      • The difference between loader and plugin
        • Loader is mainly used to convert certain types of modules. It is a converter
        • Plugin is a plug-in, which is an extension to WebPack itself, and is an extender
      • Use steps:
        • Step 1: Install the plugins you need to use through NPM

        • Step 2: Configure the plug-in in plugins in webpack.config.js


    Vue single file component

    Using Vue single-file components, each single-file component has a.vue suffix each Vue single-file component consists of three parts:

    • The template area of the template component
    • An area of business logic composed of script
    • Style area
    <template> <div>abc</div> </template> <script> export default { data() { return {}; }, methods: {}} </script> // style style scoped directive can prevent style conflicts between components <style scoped> div {color: red; } </style>Copy the code

    Vue scaffolding

    Basic usage
    Vue create my-project //2 Create vUE PROJECT VUE UI based on graphical interfaceCopy the code

    Vue scaffolding custom configuration
    1. Configure the project through package.json (not recommended)

      "Vue ": {"devServer": {"port": 8888, // Set port number "open": true // automatically open project}}Copy the code
    2. Create vue.config.js in the project root directory (recommended)

      module.exports = {
        devServer: {
          port: 8888,
          open: true
        }
      }
      Copy the code



The last

If it helps you, please like and bookmark this article and let more people see it ~ (“▔□▔)/

If you have any objections, please leave them in the comments section and I will reply one by one

If you are interested, please visitA blogger with a light in his eyes