At the forefront of

Out of the world just to observe!! I am Nezha. Re-study and consolidate your Vuejs knowledge system. If you miss any knowledge points, please explain them in the comments so that I can update the content knowledge system in time. Welcome to like collection!

What is your understanding of MVC, MVP, and MVVM?

Github.com/webVueBlog/…

Turn the corner and meet Vuejs

  1. Why do you learn Vuejs
  2. Complexity of front-end development
  3. The characteristics of Vuejs
  4. Install Vuejs
  5. Experience Vuejs
  6. MVVM architecture: Separation of data and Vue objects, MVVM in Vue

Directory:

start

  1. Interpolation syntax: Mustache, V-once, V-HTML, V-text, V-pre, V-block.
  2. Binding properties: Introduction to V-bind, the basics of V-bind, the syntax of V-bind, binding class, binding style.
  3. Calculate attribute
  4. Event listening: V-ON introduction, V-ON basics, V-ON parameters, V-ON modifiers
  5. Conditions and loops: Conditional rendering, V-show instructions, V-if and V-show contrast
  6. Form binding: Basic usage, V-Model principle, other types, value binding, modifiers.

Component development:

What is componentization, Vue componentization development idea

  1. Steps for registration
  2. Global and local components
  3. Parent and child components
  4. Register component syntax sugar
  5. Separate writing of a template
  6. Additional properties of the component
  7. Parent passes to child
  8. Child passes to parent
  9. Access to parent and child components
  10. Non-parent component communication

Componentized advanced syntax:

  1. Slot slot: compile scope, why slot is used, basic use of slot, named slot, scope slot.
  2. Dynamic components
  3. Asynchronous components
  4. Component declaration cycle

Vue Cli

  1. What is a webpack
  2. Webpack vs. Gulp
  3. Manual Webpack configuration
  4. What is Vue Cli
  5. Vue Cli depends on the environment
  6. Vue Cli installation

Network encapsulation

  1. Using traditional Ajax is based on XMLHttpRequest(XHR)
  2. Use the jQuery – Ajax
  3. Vue-resource
  4. Using axios

The use of axios

  1. Understand AXIos: The axiOS request method
  2. Send request, send GET request, send concurrent request, AXIOS global configuration, common configuration options.
  3. Axios instance, why an Axios instance is created, how an AXIos instance is created, encapsulation of Axios.
  4. Interceptors for Axios: requests and responses

Vuejs principle related: responsive principle, source code.

Vue. Js is what

  • Vue is a set of progressive frameworks for building user interfaces.
  • Applied layer by layer from bottom up, the core library only focuses on layers.
  • Easy to learn and integrate with third-party libraries or existing projects.

Vue basic syntax

For basic knowledge needed to be mastered, simply write ✍

Vue. Js installed

Direct CDN introduction:

  1. For prototyping or learning

Code: < script SRC = “https://cdn.jsdelivr.net/npm/vue/dist/vue.js” > < / script >

  1. For the production environment

Code: < script SRC = “https://cdn.jsdelivr.net/npm/[email protected]” > < / script >

  1. NPM

Code:

$NPM install vueCopy the code

Vue responsive first experience

Declarative programming:

Code:

<! DOCTYPE html> <! < HTML >< head> <meta charset=" utF-8 "> <title></title> <script SRC ="vue.js" type="text/javascript" charset="UTF-8"></script> <! -- <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> --> </head> <body> <div id="app"> {{ a }} </div> <script type="text/javascript"> // Var data = {a: 1}; Var vm = new Vue({el: "#app", data: data}); // data.a = "dada" vm.a = "qianduan"; data.a == vm.a; </script> </body> </html>Copy the code

Small case – calculator

  1. New properties:methods, this property is used forVueA method defined in the.
  2. New instructions:@clickThis directive is used to listen for a click event on an element and needs to specify the method to execute when a click occurs.

Code:

<div id="app"> <h1> Current count {{counter}}</h1> < butt@click ="increment">+</ butt@click ="decrement">-</ buttonset > </div> <script src=".. /js/vue.js"></script> <script> let app = new Vue({ el: '#app', data: { counter: 0 }, methods: { increment(){ this.counter++ }, decrement(){ this.counter-- }, } }) </script>Copy the code

The Vue MVVM

The thought of the MVVM

  1. View is our DOM
  2. Model is obJ that we pulled out
  3. The ViewModel is the Vue object instance we created

How do they work with each other?

  1. The ViewModel allows Data in OBJ to be displayed in the DOM in real time through a Data Binding
  2. The ViewModel listens for DOM events through DOM Listeners and changes the data in OBJ through operations in Methods

  • elType:string | HTMLElement
  • Role: Determines which Vue instances will be managed laterDOM
  • dataType:Object | Function
  • Action: Data object corresponding to Vue instance
  • methodsType:{[key:string]:Function}
  • What it does: Defines methods that belong to the Vue and can be called elsewhere or used in directives.

What is the Vue lifecycle

▌ Life cycle: The whole process of a thing from birth to death

  • releaseStable version
  • debugversion
  1. Mustache syntax is basically double curly braces
  2. The interpolation operation
  3. Binding properties
  4. Calculate attribute
  5. events
  6. To iterate over
  7. Phase case
  8. v-model

The use of the V-once command

<div id="app">
 <h1>{{message}}</h1>
 <h2 v-once>{{message}}</h2>
</div>
Copy the code

V – once:

  1. This instruction does not need to be followed by any expression
  2. This directive indicates that elements and components are rendered only once and do not change as the data changes

V – HTML:

When the data we request from the server is itself an HTML code

  1. If you go straight through{{}}To output, will beHTMLThe format is parsed and the corresponding content is displayed.
  2. You can usev-htmlinstruction
  3. This command is followed by onestringtype
  4. willstringthehtmlParse and render
<h1 v-html="url"></h1>
Copy the code

V-text is more similar to Mustache in that it is used solely to display data in the interface and generally accepts a string.

<div id="app"> <h2 v-text="message"></h2> <h2>{{message}}</h2> </div> <script src=".. </script> <script> let vm = new vue ({el: '#app', data: {message: 'hello'}}) </script>Copy the code

The V-pre is used to skip compilation of this element and its children and to show the original Mustache syntax.

<div id="app"> <p v-pre>{{message}}</p> </div> <script src=".. /js/vue.js"></script> <script> let app = new Vue({ el: '#app', data: { message: 'hello' } }) </script>Copy the code

A v-cloak is a cloak.

<div id="app">
 <h2 v-cloak>hello{{name}}</h2>
</div>
<script>
 setTimeout(()=>{
     let app = new Vue({
      el: '#app',
      data: {
          name: 'web'
      }
     })
 },10000)
</script>

<style>
 [v-cloak] {
     display: none;
 }
</style>
Copy the code

The introduction of v – bind

V-bind is used to bind one or more property values, or to pass props values to another component.

<div id="app">
 <a v-bind:href="link">vuejs</a>
 <img v-bind:src="url" alt="">
</div>

<script>
 let app = new Vue({
  el: '#app',
  data: {
      
  }
 })
Copy the code

V – bind syntactic sugar

V-bind has a syntactic equivalent, the shorthand

<div id = "app">
    <a :href="link">vuejs</a>
    <img :src="longURL" alt="">
</div>
Copy the code

V-bind dynamically binds the class

<style>
 .active{
     color: red;
 }
</style>

<div id="app">
 <h1 class="active">{{message}}</h2>
</div>

<script>
 const app = new Vue({
  el: '#app',
  data: {
      message: 'hello'
  }
 })
</script>
Copy the code

There are two ways to bind a class:

  1. Object syntax
  2. Array syntax

Object syntax:

<h2 :class="{'active': isActive}">hello</h2> <h2 :class="{'active': isActive, 'line': IsLine}"> </h2> <h2 class="title" :class="{'active': IsActive}"></h2> Can be put in a methods or computed method </h2>Copy the code

V-bind dynamically binds class, array syntax

<div id="app">
 <h2 class="title" :class="[active, line]">{{mesg}}</h2>
 <h2 class="title" :class="getClasses()">{{mesg}}</h2>
</div>

<script>
 const app = new Vue({
     el: '#app',
     data: {
         message: 'hello',
         active: 'aaa',
         line: 'bbb',
     },
     methods: {
         getClasses: function() {
             return [this.active, this.line]
         }
     }
 })
</script>
Copy the code

V-bind dynamically binds style

Object syntax and array syntax are bound.

Object syntax:

:style="{ color: currentColor, fontSize: fontSize + 'px' }"
Copy the code

Style is followed by an object type. The key of the object is the name of the CSS property, and the value of the object is the assigned value. The value can come from a property in data.

Binding method: Array syntax:

<div v-bind:style="[baseStyles, overStyles]"></div>
Copy the code

Style is followed by an array type, multiple values, split.

Evaluate the base properties of the property

Calculate the attributes, written in the computed option of the instance:

<div id="app">
 <h2>{{firstName}}{{lastName}}</h2>
</div>

<script>
 const vm = new Vue({
  el: '#app',
  data: {
      firstName: 'web',
      lastName: 'it',
  }
 })
</script>
Copy the code
<div id="app">
 <h2>{{fullName}}</h2>
</div>

<script>
 const vm = new Vue({
  el: '#app',
  data: {
      firstName: 'jeskson',
      lastName: 'it',
  },
  computed: {
      fullName() {
          return this.firstName + ' ' + this.lastName
      }
  }
 })
</script>
Copy the code

Calculate the cache of attributes:

Why do you use computed properties?

Reason: Calculated properties are cached and only called once if used more than once.

Setter and getter

Each computed property contains a getter and a setter

<div id="app">
 <div>{{fullName}}</div>
 <div>{{firstName}}</div>
 <div>{{lastName}}</div>
</div>

<script>
 let vm = new Vue({
  el: '#app',
  data: {
      firstName: 'web',
      lastName: 'it',
  },
  computed: {
      fullName: {
          get() {
              rturn this.firstName+" "+this.lastName
          },
          set(newValue){
              const names = newValue.split(' ')
              this.firstName = names[0]
              this.lastName = names[1]
          }
      }
  }
 })
</script>
Copy the code
Computed: {fullName: function() {return this.firstname +" "+ this.lastname} // Generally, there is no set method for computing attributes, only attributes. fullName: { get: function() { return this.firstName + " " + this.lastName } } }Copy the code

The use of the const

Use of const. In JavaScript, we use const – modified identifiers as constants that cannot be reassigned.

In ES6 development, const is preferred and let is used only when an identifier needs to be changed.

To define an identifier using cost, an assignment must be made.

Constant means that the object you point to cannot be modified, but you can change properties inside the object.

When do you use const?

We can use const to keep the data safe when the identifier we decorate will not be reassigned.

Use of const:

const a=20; a = 10; // error: const name cannot be modified; // Error, const qualifier must be assignedCopy the code

Let and var

Block-level scope:

JS uses var to declare a variable. The scope of the variable is mainly related to the definition of the function.

Other block definitions that are not scoped, such as if/for, often cause problems during development.

/ / to monitor button click var BTNS = document. The getElementsByTagName (" button "); for(var i=0; i<btns.length; I++) {(function (I) {BTNS [I] onclick = function () {alert (' click on the '+ I + "a")}}) (I)}Copy the code
let btns = document.getElementsByTagName('button'); for(let i=0; i<btns.length; I++) {BTNS [I] onclick = function () {alert (' click on the '+ I +' a ')}}Copy the code

Block-level scope

Variable scope: The scope in which a variable is available.

var func;
if(true) {
    var name = 'web';
    func = function() {
        console.log(name); // web
    }
    
    func(); // web
}

// name = 'it'
func(); // web -> it
console.log(name); // web -> it
Copy the code

There are no problems with block level scope, block level for

var btns = document.getElementsByTagName('button'); for(var i=0; i<btns.length; I ++) {BTNS [I].adDeventListener ('click', function(){console.log(' first '+ I +'); })}Copy the code

Closure:

var btns = document.getElementsByTagName('button'); for(var i=0; i<btns.length; I++) {(function (I) {BTNS [I] addEventListener (' click ', function () {the console. The log (' first '+ I +' buttons'); }) })(i) }Copy the code

The reason closures work is because a function is a scope.

Enhanced writing of an object

Short for property initializer and method:

Let name = 'web' let age = 12 let obj1 = {name: name, age: age,} console.log(obj1); // let obj2 = {name, age} console.log(obj2)Copy the code
Let obj1 = {test: function() {console.log('obj1')}} obj1.test(); // es6 let obj2 = {test() {console.log('obj2')}} obj2.test();Copy the code

V – on the foundation

v-on:click="counter++"

<div id="app"> <h2> < {counter}}</h2> <button V-on :click="counter++"> </button> </button </button> </div> let app = new Vue({el: '#app', data: {counter: 0}, methods: { btnClick(){ this.counter++ } } })Copy the code

The use of the V-ON modifier

<div id="app"> <div @click="divClick"> < [email protected] ="btnClick">Copy the code

Vue provides some modifiers:

.stop calls Event.stopPropagation (). Prevent calls event.preventDefault(). Native listens for the component's root element's native event.once to trigger only one callbackCopy the code
<button @click.stop="doThis"></button> // prevent="doThis"></button> </form> </form> </form> // concatenation modifier < [email protected]. prevent = "doThis"></button> Key alias < input@keyup. enter="onEnter"> // Key modifier, <button @click.once="doThis"></button>Copy the code

v-if,v-else-if,v-else

Simple use:

< div id = "app" > < p v - if = "score > = 90" > good < / p > < p v - else - if = "score > = 80" > good < / p > < p v - else - if = "score > = 60" > in < / p > < p V-else ="score<60"> Fail </p> </div>Copy the code

Login switch:

< div id = "app" > < span v - if = "type = = = 'username'" > < label > user accounts: </label> <input placeholder=" user account "> </span> < SPAN v-else> <label> </label> <input placeholder=" email address "> </span> <button @click="handleToggle"> </button> </div> <script> let app = new Vue({ el: '#app', data: { type: 'username' }, methods: { handleToggle(){ this.type = this.type === 'email' ? 'username' : 'email' } } }) </script>Copy the code
<div id="app"> <span v-if="isUser"> <label for="username"> </label> <input type="text" id="username" Placeholder =" user account "> </span> <span V-else > <label for="email"> </label> <input type="text" ID ="email" Placeholder =" placeholder "> </span> <button @click="isUser=! </button> </div> const app = new Vue({el: '#app', data: {isUser: true}}) </script>Copy the code

V-for traverses the object

<div id="app">
 <ul>
  <li v-for="(value, key, index) in info">
   {{value}}-{{key}}-{{index}}
  </li>
 </ul>
</div>

<script>
 let app = new Vue({
  el: '#app',
  data: {
      info: {
          name: 'web',
          age: 12,
      }
  }
 })
</script>
Copy the code

The component’s Key property

With V-for, add a :key attribute to the corresponding element or component.

The key’s main purpose is to update the virtual DOM efficiently.

Which methods in the array are reactive

Push () 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 splice() sort() reverse()Copy the code

The shopping cart

< div id = "app" > < table > < thead > < tr > < th > < / th > < th > books name < / th > < th > publication date < / th > < th > price < / th > < th > purchase quantity < / th > < th > action < / th > < / tr > </thead> <tbody> <tr v-for="item in books"> <td v-for="value in item">{{value}}</td> </tr> </tbody> </table> </div>Copy the code

Form binding V-Model

The V-model directive is used in VUE to implement bi-directional binding between form elements and data.

<div id="app">
 <input type="text" v-model="message">
 <h2>{{message}}</h2>
</div>
Copy the code

Reduce summarizes all the contents of an array.

JavaScript the reduce () method

var numbers = [65, 44, 12, 4];
 
function getSum(total, num) {
    return total + num;
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
Copy the code

Definitions and Usage

The reduce() method takes a function as an accumulator, and each value in the array (from left to right) starts to shrink and eventually evaluates to a value.

Reduce () can be used as a higher-order function for compose of functions.

Note: Reduce () does not perform a callback for an empty array.

grammar

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
Copy the code

The use and principle of V-Model

<input type="text" :value="message" @input="message = $event.target.value"> <script> const app = new Vue({ el: }, methods: {valueChange(event){this.message = event.target.value; } } }) </script>Copy the code

V-models are syntactic sugar, essentially:

  1. v-bindBind avalueattribute
  2. v-onThe directive binds the current elementinputThe event

Code:

<input type="text" v-model="message">

<input type="text" v-bind:value="message" v-on:input="message = $event.target.value">
Copy the code

v-model:checkbox

Check boxes are classified into two types: single check box and multiple check boxes.

Single check box:

V-model is a Boolean value. The input value does not affect the value of the V-model.

Multiple check boxes:

In the case of multiple check boxes, the property in the corresponding data is an array.

When one of them is selected, the value of the input is added to the array.

<div ID ="app"> <label for="check"> <input type="checkbox" V-model ="checked" ID ="check"> Agree protocol </label> <label><input Type ="checkbox" v-model="hobbies" value=" basketball "> basketball </label> <label><input type="checkbox" v-model="hobbies" </label> </div>Copy the code

v-model:select

Select indicates either single selection or multiple selection

Single: Only one value can be selected. Multiple: Multiple values can be selected.

v-modelIn combination withselecttype

Like checkbox, select can be either single or multiple.

Single, can only select a value, v-model binding is a value. When we select one of the options, we assign its corresponding value to mySelect.

Multiple selection, multiple values can be selected. The V-Model binds to an array. When multiple values are selected, the value corresponding to the selected option is added to the array mySelects.

// Select a value <select V-model ="mySelect"> <option value="web">web</option> <option value="it">it</option> </select> <p> your favorite {{mySelect}}</p> // Select multiple values <select V-model ="mySelects" multiple> <option value="web">web</option> <option Value = "it" > it < option > < / select > < p > your favorite {{mySelects}} < / p >Copy the code

Value binding in input

<label v-for="item in origin">
 <input type="checkbox" :value="item" v-model="hobbies">
 {{item}}
</label>
Copy the code

The modifier

Lazy decorator:

  1. By default,v-modelThe default is ininputEvent to synchronize data from the input box.
  2. Once there is a change in the data corresponding todataThe data is automatically changed.
  3. lazyModifiers can cause data to be updated only when it loses focus or returns.

The number modifier:

  1. By default, whether we enter letters or numbers in the input field is treated as a string.
  2. But if we want to deal with numeric types, it’s better to treat the content as a number.
  3. numberModifiers automatically convert what is entered in an input field to a numeric type.

Trim modifier:

  1. If the input has a lot of white space at the beginning and end, we usually want to remove it
  2. trimModifiers filter Spaces on the left and right sides of content

Example:

<div id="app">
 <input type="text" v-model.lazy="message">
 <h2>{{message}}</h2>
</div>
Copy the code

What is componentization

  1. Componentization is an important idea in vue.js
  2. It provides an abstraction that allows us to develop individual reusable widgets to construct our applications
  3. Any application is abstracted into a tree of components

Basic steps to register a component:

  1. Create the component constructor
  2. Certified components
  3. Using the component

Example:

The Vue.component() method is called to register the component to use the component within the scope of the Vue instanceCopy the code

Component examples:

<div id="app"> <my-cpn></my-cpn> </div> <script src=".. /js/vue.js"></script> <script> // create component constructor const myComponent = vue.extend ({template: '<div> <h2> Component title </h2> <p> Component paragraph </p> </div>'}); Vue.component('my-cpn',myComponent); </script>Copy the code

Global components and local components

  1. Vue.extend()callVue.extend()Create a component constructor.
  2. Normally passed when creating a component constructortemplateA template that represents our custom component.
  3. The template is displayed where the component is usedhtmlThe code.
  4. This is written inVue2.xThe files are almost invisible.
  5. Vue.component()Register the component constructor as a component and give it the tag name of the component.
  6. Register the tag name of the component, component constructor.

Example:

The component title < div id = "app" > < my - CPN > < my - CPN > < div > < my - CPN > < my - CPN > < / div > < / div >Copy the code

Example:

<div id="app1"> <my-cpn></my-cpn> </div> <div id="app2"> <my-cpn></my-cpn> </div> <script src=".. /js/vue.js"></script> <script> // create component constructor const myComponent = vue.extend ({template: ` < div > < h2 > web < / h2 > < / div > `}) / / Vue.com registered components ponent (' my - CPN, myComponent); let app1 = new Vue({ el: '#app1' }) let app2 = new Vue({ el: '#app2' })Copy the code
< div id = "app1" > < my - CPN > < / my - CPN > < / div > < div id = "app2" > / / not be rendered out < my - CPN > < / my - CPN > < / div > < script SRC = ".. /js/vue.js"></script> <script> // create component constructor const myComponent = vue.extend ({template: ` <div> <h2>web</h2> </div> ` }) let app1=new Vue({ el: '#app1', components: { 'my-cpn': myComponent } }) let app2 = new Vue({ el: '#app2' }) </script>Copy the code

Parent and child components

The component tree

  1. There is a hierarchy between components
  2. One of the most important relationships is the parent-child component relationship

Example:

<div id="app"> <parent-cpn></parent-cpn> </div> <script src=".. /js/vue.js"></script> <script> // create a childComponent constructor const childComponent = vue.extend ({template: '<div> I am the content of the child component </div>'}) // create a parentComponent constructor const parentComponent = vue.extend ({template: '<div> I am the content of the parent component <child-cpn></child-cpn> </div>' components: {'child-cpn': childComponent } }) let app = new Vue({ el: '#app', components: { 'parent-cpn': parentComponent } })Copy the code

Register component syntax sugar

Example: Global component

<div id="app"> <cpn1></cpn1> </div> <script> vue.component ('cpn1', {template: ` <div> <h2>web</h2> </div> ` }) const app = new Vue({ el: '#app', data: { message: 'web', } }) </script>Copy the code
<div id="app"> <cpn2></cpn2> </div> const app = new Vue({el: '#app', data: {message: 'web' }, components: { 'cpn2': { template: ` <div> <h1>web</h1> </div> ` } } }) </script>Copy the code

Vue simplifies the way components are registered, providing syntactic sugar for registration.

The way to write component templates detached

Vue provides two ways to define HTML module content:

  1. use<script>The label
  2. use<template>The label

Example:

<div id="app"> <my-cpn></my-cpn> </div> <script type="text/x-template" id="myCpn"> <div> <h2>web</h2> </div> </script> <script src=".. /js/vue.js"></script> <script> let app = new Vue({ el: '#app', components: { 'my-cpn': { template: '#myCpn' } } }) </script>Copy the code

The template tag

<template id=" CPN "> <div> <h2>web</h2> </div> </template>Copy the code

Does the component have access to vUE instance data

A component is a single functional module encapsulation with its own HTML template and its own data.

Component objects have a data attribute, methods attribute, which must be a function that returns an object and holds data inside the object.

<div id="app"> <my-cpn></my-cpn> </div> <template id="myCpn"> <div>{{message}}</div> </template> <script src="..." ></script> <script> let app = new Vue({ el: '#app', components: { 'my-cpn': { template: 'myCpn', data() { return{ message: 'web' } } } } })Copy the code

Father to son. – Father to son props

How do you communicate between parent and child components?

  1. throughpropsPass data to child components
  2. Send messages to the parent component through events

Basic usage of props

In the component, use props to declare the data received from the parent

The value of the props:

  1. Array of strings, and the string in the array is the name of the pass.
  2. Object, object can be set when the type of transfer, can also set the default value, etc.

CamelCase prop names need to be named using their equivalent Kebab-case (dash delimited naming) :

Vue.component('blog-post', {// in JavaScript is the props of camelCase: ['postTitle'], template: '<h3>{{ postTitle }}</h3>' }) <! <blog-post post-title=" Hello!" ></blog-post>Copy the code

Again, if you use a string template, this limitation does not exist.

The respective names and types of prop:

props: {
 title: String,
 likes: Number,
 isPublished: Boolean,
 commentIds: Array,
 author: Object,
 callback: Function,
 contactsPromise: Promise // or any other constructor
}
Copy the code
<! --> <blog-post v-bind:title="post.title"></blog-post> <! --> <blog-post v-bind:title="post.title + 'by' + post.author.name" ></blog-post> <! Even though '42' is static, we still need 'V-bind' to tell Vue --> <! This is a JavaScript expression, not a string. --> <blog-post v-bind:likes="42"></blog-post> <! Dynamic assignment with a variable. --> <blog-post v-bind:likes="post.likes"></blog-post>Copy the code

Pass in all attributes of an object

If you want to pass in all the properties of an object as prop, you can use v-bind with no arguments (instead of V-bind :prop-name) :

post: {
  id: 1,
  title: 'My Journey with Vue'
}

<blog-post v-bind="post"></blog-post>

<blog-post
  v-bind:id="post.id"
  v-bind:title="post.title"
></blog-post>
Copy the code

A simple props pass:

<div id="app"> <child-cpn :message="message"></child-cpn> </div> <template id="childCpn"> <div> {{message}}</div> </template> <script> let app = new Vue({ el: '#app', data: { message: 'hello' }, components: { 'child-cpn': { templte: '#childCpn', props: ['message'] } } }) </script>Copy the code

In Vue, the relationship between parent and child components

Props passes down, events pass up.

The parent component sends data to the child component through props, and the child component sends messages to the parent component through events.

Supported data types:

String

Number

Boolean

Array

Object

Date

Function

Symbol
Copy the code

Example:

Vue.component('my-component',{props: {// Basic type check propA: Number, // multiple possible types propB: [String, Number], // propC: {type: String, required: true}, // propD: {type: Number, default: 100}, // Object with default propE: {type: Object, default: function(){return {message: 'web'}}}, // custom validation function propF: {vfunc: function(value) { return value > 1 } } } })Copy the code

Child the parent

Code:

this.$emit('item-click',item)
Copy the code

Functions are used by a parent component to pass data to a child component, or, more commonly, by a child component to pass data or events to a parent component.

Custom events:

  1. In the child component, pass$emit()To trigger the event.
  2. In the parent component, passv-onTo listen for child component events.

Custom event code:

<div ID ="app"> <child-cpn @increment="changeTotal" @decrement="changeTotal"></child-cpn> <h2> Number of hits </h2> </div> <template id="childCpn"> <div> <button @click="increment">+1</button> <button @click="decrement">-1</button> </div> </template> let app = new Vue({ el: '#app', data: { total: 0 }, methods: { changeTotal(counter) { this.total = counter } }, components: { 'child-cpn': { template: '#childCpn', data(){ return{ counter: 0 } }, methods: { increment(){ this.counter++; this.$emit('increment', this.counter) }, decrement(){ this.counter--; this.$emit('decrement',this.counter) } } } } })Copy the code

Parent and child components can be accessed by:$children

Sometimes you need the parent to directly access the child, the child to directly access the parent, or the child to access the parent.

  1. The parent component accesses the child component using$childrenor$refs
  2. The child component accesses the parent component using$parent

For $Children:

  1. this.$childrenIs an array type that contains all child component objects.
  2. Fetch the values of all child components by traversingmessageState.

Example:

<div id="app"> <parent-cpn></parent-cpn> </div> // parent component template <template id="parentCpn"> <div> <child-cpn1></child-cpn1> <child-cpn2></child-cpn2> < button@click ="showChildCpn"> Display all child components </button> </div> </template> // child <template Id ="childCpn1"> <h2> I am child component 1</h2> </template> Vue.component('parent-cpn',{ template: '#parentCpn', methods: { showChildCpn(){ for(let i=0; i<this.$children.length; i++){ console.log(this.$children[i].message) } } } })Copy the code

Parent and child components can be accessed by:$parent

The parent component can be accessed directly from the child component via $parent

  1. Although it can pass$parentTo access the parent component, but try not to do so
  2. The child component should avoid direct access to the parent component’s data because it is too coupled.

Parent and child components are accessed by $refs

Defects of $children:

  1. through$childrenAccess subcomponents, which is an array type, are accessed through index values.
  2. If there are too many sub-components and you need to take one of them, you cannot determine its index value and it may change.
  3. Gets one of the specific components that you can use$refs

Use of $refs:

  1. $refsandrefInstructions are usually used together
  2. throughrefBind a specific to a child componentid
  3. throughthis.$refs.idThis component can be accessed

Example:

<child-cpn1 ref="child1"></child-cpn1> <child-cpn2 ref="child2"></child-cpn2> <button @click="show">  show() { console.log(this.$refs.child1.message); console.log(this.$refs.child2.message); }Copy the code

Look at a.vue file project

<template>
 <div class="xxx">
  <div class="xxx"
   :class="{active: currentIndex === index}"
   @click="itemClick(index)"
   v-for="(item,index) in titles">
   <span>{{item}}</span>
   </div>
  </div>
</template>

<script>
 export default {
     name: 'xxx',
     props: {
         titles: {
             type: Array,
             default() {
                 return []
             }
         }
     },
     data: function() {
         return {
             currentIndex: 0
         }
     },
 }
</script>

<style scoped>
 .xxx {
     xxx: xxx;
 }
</style>
Copy the code

Three-layer part:

Slot Slot usage

What is the code slot in Vue? It is called a slot. The

element acts as a content distribution slot in the component template.

V – slot usage:

  1. The default slot
  2. A named slot
  3. Scope slot
  4. slotAs well asslot-scopeUse: child component write, parent component write

The default slot

Child components:

// Subcomponent <template> <div class="content"> // Default slot <content-box class="text"> <slot> Default value </slot> <content-box> </div> </template>Copy the code

Slot basic usage

  1. In a child component, use<slot>You can open a slot for child components.
  2. What the slot inserts depends on how the parent component is used.

The child component defines a slot:

  1. <slot>Represents that the modified content is displayed by default if nothing else has been inserted into the component.

Example:

< div id = "app" > < my - CPN > < / my - CPN > < my - CPN > < p > web < / p > < / my - CPN > < / div > < template id = "myCpn" > < div > < slot > I am < / slot > </div> </template> <script> Vue.component('my-cpn',{ template: '#myCpn' }) let app = new Vue({ el: '#app' }) </script>Copy the code

Use named slots

  1. toslotElement to add anameattribute
  2. <slot name="web"></slot>

Example:

<div id="app"> // Nothing <my-cpn></my-cpn> // pass something <my-cpn>< span slot="left">left</span> </my-cpn> <my-cpn>< span slot="left">left</span> <span slot="center">center</span> <span slot="right">right</span> </div> <template id="myCpn"> <div> <slot name="left">1</slot> <slot name="center">2</slot> <slot name="right">3</slot> </div> </template> <script> Vue.component('my-cpn', { template: '#myCpn' }) let app = new Vue({ el: '#app' }) </script>Copy the code

Compile scope

Vue instance attributes:

Everything in the parent component template is compiled in the parent scope, and everything in the child component template is compiled in the child scope.

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

Modular development

What is modularity? The process of stitching together a set of modules into a file in the right order. A module is the encapsulation of a set of properties and methods that implement a particular function.

Use constructors to encapsulate objects

function web() {
    var arr = [];
    this.add = function(val) {
        arr.push(var)
    }
    this.toString = function() {
        return arr.join('')
    }
}
var a = new web();
a.add(1); // [1]
a.toString(); // "1"
a.arr // undefined
Copy the code

Example:

Var ModuleA = (function(){// Define an object var obj = {} // Add variables and methods inside the object obj. Flag = true obj. MyFunc = function(info) { console.log(info) }; // return object obj}Copy the code
if(ModuleA.flag) {
    console.log('web')
}

ModuleA.myFunc('webweb')
Copy the code

Common modular specifications:

CommonJS, AMD, CMD, ES6 in Modules

What is AMD, asynchronous module definition, it is a specification to implement modular development in the browser side, but this specification is not supported by native JS, the use of AMD specification development needs to introduce a third party library function, namely RequireJS.

RequireJS solves the problem that multiple JS files may have dependencies, and the dependent files need to be loaded into the browser before the dependent files. The browser will stop rendering when js is loaded. The more files loaded, the longer the page will be unresponsive.

CMD is a generic module definition that solves the same problems as AMD, but in terms of how modules are defined and when modules are loaded, CMD requires the addition of SeaJS, a third-party library file.

JavaScript modular programming

  1. Can solve the problem of global variable pollution in the project
  2. High development efficiency, conducive to collaborative development of many people
  3. Single responsibility, easy code reuse and maintenance
  4. Resolved file dependency issues

So what is modularity

Divide a project according to function, theoretically one function and one module, do not affect each other, load when needed, try to follow high cohesion and low coupling.

Understand the CommonJS

CommonJS is an idea that is essentially reusable JavaScript that exports specific objects for other programs to use.

Export objects using module.exports and exports.obj and load them using require(‘module’) in programs that need it.

The core of modularity is: import and export

Export: CommonJS

module.exports = {
    flag: true,
    test(a,b) {
        return a+b
    },
    demo(a,b) {
        return a*b
    }
}
Copy the code

Import: CommonJS

// CommonJS module let {test, demo, flag} = require('moduleA'); // => let ma = require('moduleA'); let test = ma.test; let demo = ma.demo; let flag = ma.flag;Copy the code

As web development becomes more complex and js files become more numerous, some problems arise:

  1. Variable name conflict
  2. File dependency complexity is high
  3. Too many pages are loaded, which is inconvenient for maintenance

A single JS file is a module. Each module has its own scope. Variables defined inside the module cannot be read by other modules, except for attributes defined as global objects.

Exports of modules: exports and module.exports

Module import: require

  1. innodeEach module has its own insidemoduleobject
  2. inmoduleObject, there is one memberexportsIt’s also an object
  3. throughexportsObject to export the current method or variablemodule.exportsexport
  4. nodeSimplifies operations,exportsIs equal to themodule.exports, which is equivalent tovar exports = module.exports

Es module import and export

export function add(num1, num2) {
    return num1 + num2
}
Copy the code
Export function accString(param) {if(param == 0) {return 'off'}else if(param == 1) {return 'on'}} import {accString  } from '.. /.. /utils'Copy the code
const name = 'web'

export default name
Copy the code

export default

If you do not want to name a function in a module, you can let the importer decide:

export default function(){
    console.log('web')
}
Copy the code

Use:

import myFunc from '.. /web.js' myFunc()Copy the code

Export default cannot exist in the same module

Use the import

The export directive exports the interface provided by the module

The import directive is used to import the contents of a module

import {name, age} from './web.js'
Copy the code

You can import all of the export variables in the module with *

import * as web from './web.js'

console.log(web.name);
Copy the code

The last

I am programmer Doraemon, Blue Fat man, excellent creator of Jian Shu Wan Fan, excellent author of Nuggets, EXPERT of CSDN blog, and active author of Cloud + community. I am committed to creating A series of high-quality articles that can help programmers improve. Website @ www.dadaqianduan.cn