Vue component development

Vue component development

  1. Use of JavaScript higher-order functions

    Programming paradigm can be divided into: imperative programming (JS) and declarative programming (Vue); Or object-oriented programming (First Citizen: object) and functional programming (First Citizen: function);

    JS advanced functions can realize chain programming!! This kind of programming is called functional programming; For example, for the arrow function, first filter to find values less than 100, then multiply these values by 2, and then calculate the sum of these values:

    let total = nums.filter(n=> n < 100).map(n=> n*2).reduce((pre,n)=> pre+n);

    filter function

    - the passed in parameter is a callback function, which can iterate over elements;

    - Syntax: list.filter(function(n) {});

    - the callback function passed in by this function has a requirement: it must return a Boolean value; When true is returned, the parameter n in the callback function will be automatically added to the new array; When false is returned, the callback function will automatically filter out the element;

    For example:

    <script>
    //You can directly extract the elements less than 100 in the array
    	const nums = [10,20,111,34,201,50]
    let list = nums.filter(function(n){
      return n<100
    })
    </script>
    

    map function

    - the passed in parameter is a callback function, which can iterate over elements;

    - the callback function passed in by the function will directly return the element or the element processed by the operation;

    For example:

    <script>
     //Returns a new array of 2 times the number of array elements
    	const nums = [10,20,30,40]
     let list = nums.map(function(n){
         return n*2
     })
    </script>
    

    reduce function

    - function: it can summarize all elements in the array;

    - two parameters need to be passed in. Parameter 1 is a callback function and parameter 2 is 0, which is equivalent to the initialization value of 0;

    - the callback function also needs to pass in two parameters. The first parameter is the value returned by the previous loop traversal (the value returned by the first loop traversal is the initialization value), and the second parameter is the element value of the loop traversal;

    For example:

    <script>
    	//Returns the sum of arrays
     const nums = [10,20,30,40]
     let sum = nums.reduce(function(preValue,n){
         return preValue+n
     },0)
     //analysis:
     //First preValue:0 n:10
     //Second preValue: 0+10 n:20
     //Third preValue: 0+10+20 n:30
     //Prevalue for the fourth time: 0 + 10 + 20 + 30 n: 40 return 0 + 10 + 20 + 30 + 40
    </script>
    
  2. assembly

    - basic idea: putting all the processing logic in a page together will be complex, not for example, subsequent management and expansion. However, if the page is divided into small function blocks, and each function block completes its own independent functions, the management and maintenance of the whole page is very easy;

    - componentization is an important idea in Vue. It provides an abstraction so that we can develop independent reusable small components to construct our applications; Any application will be abstracted into a component tree; (this involves tree structure and binary tree in data structure)

    Basic steps for registering components

    - create component constructor: call Vue.extend() method;

    - register component: call Vue.component() method; (here is a global component)

    - use components: use components within the scope of Vue instances;

    - register the syntax sugar form of the component, omitting the Vue.extend() method and directly using an object instead:

    <script>
    //Registration syntax for global components
    	Vue.component('cpn',{
      template:`
    			<div>
    			<h2>I'm a title</h2>
    		</div>
    		`
    })
     const app = new Vue({
         el:'#app',
         data(){
    
         },
         //Syntax of local components
         components:{
             'cnp2':{
                 template:`
    					<div>I am a local component<div>
    				`
             }
         }
     })
    </script>
    

    Basic usage examples of componentization:

    <div id="app">
    <!--Create components to make them reusable-->
    <h2>I'm the title</h2>
    <p>I am the content</p>
    <!--To invoke a component, you must Vue Only within the scope of the instance can it be effective-->
    <my-cpn></my-cpn>
    </div>
    <script src="vue.js"></script>
    <script>
    //1. Create component construction object
    //ES6 syntax, string can use ` ` instead of '', so that the content in ` ` can be wrapped
    const cpnel = Vue.extend({
      //Pass in template as a template for custom components
      template:
      `<div>
    			<h2>I'm the title</h2>
    			<p>I am the content</p>
    	</div>`
    })
    //2. Register components
    //Pass two parameters, the first is the component tag name, and the second is the component construction object
     Vue.component('my-cpn',cpnel)
    //Vue instance object 
    	const app = new Vue({
      el:"#app",
      data:{
    
      }
    })
    </script>
    

    Global and local components

    - Global components can be used under multiple Vue instances;

    - local components: components registered under the components attribute in Vue instances are local components and cannot be used in other instances:

    <script>
    const cpnel = Vue.extend({
      //Pass in template as a template for custom components
      template:
      `<div>
    			<h2>I'm the title</h2>
    			<p>I am the content</p>
    	</div>`
    })
    	const app = new Vue({
      el:"app",
      data:{
    
      },
      //Register local components under a single Vue instance object
      component:{
          //Component tag name: component constructor
          cpn:cpnel
      }
    })
    </script>
    

    Parent and child components

    - Vue can be regarded as the top-level component, root component;

    <script>
    	//Create the first component constructor
     const cpnC1 = Vue.extend({
         template:
         `<div>
     		<h2>I am a title 1</h2>
     	</div>`
     })
     //Create a second component constructor
     const cpnC2 = Vue.extend({
       template:
         `<div>
     		<h2>I am a title 2</h2>
    			<cpn1></cpn1>
     	</div>`,
         //Register component 1 in component constructor 2 so that component constructor 2 is the parent component and component constructor 1 is the child component
         components:{
             cpn1:cpnC1
         }
     })
    </script>
    

    - incorrect usage of parent-child components: used in Vue instances in the form of child tags; Because when a child component is registered with the components of the parent component, Vue will compile the modules of the parent component; The content of the module has determined the page to be rendered by the parent component, which is equivalent to that the parent component already has the content of the child component; Child component labels can only be used in parent components;

    Communication between parent and child components

    - in the development process, some data is often transmitted from the upper layer to the lower layer. For example, a page requests a lot of data from the server, and some of the data needs to be displayed by the following sub components. At this time, instead of sending a network request, the parent component directly transmits the data to the sub components;

    - two ways of communication between father and son:

    1. The parent component transmits data to the child component through props;
    2. The child component sends a message to the parent component through a custom event;

    Pass data to subcomponents through props

    Method 1: string array. The string in the array is the name when passing; Rarely used in development;

    Method 2: object. The object can set the type during transmission or set the default value;

    - note that when v-bind binding is used, the hump identification name will make errors and need to be converted, such as converting childMyMessage to child my message;

    - the parent component passes the data instance to the child component through props:

    <div id = "app">
    <!--Be sure to use it when passing data here v-bind Bind-->
    <!--Note that when using v-bind During binding, the hump identification name will be in error and needs to be converted-->
    <cpn v-bind:c-movies="movies"></cpn>
    </div> 
    <template id = "cpn">
    <div>
       <ul>
           <li v-for = "item in cmovies">{{item}}</li>
       </ul>
    </div>
    </template>
    <script>
    const cpn = {
      template:'#cpn',
      //Array type
      props:['cmovies'],
      //Object form
      props:{
          //You can limit the type, and the transfer type is required to be array type
          //If the type is an object or array, the default value must be a function
          cMovies:{
              type:Array,
              default(){
                  return []
              }
          }
          //Default values can be provided
          cmessage:{
          	type:String,
          	default:'aaaa',
             //When data transfer is required, the cmessage content must be transferred, otherwise an error will be reported
              required:true
      	}
      },
      data(){
          return{}
      }
    }
    	const app = new Vue({
      el:"#app",
      data:{
          movies:["Tom","Jack","Ammy"]
      },
      components:{
          //Local component, object ES6 writing method
          cpn
      }
    })
    </script>
    

    - the child component passes data to the parent component

    - when a child component transmits data to a parent component, a user-defined event is required. v-on can be used not only to listen for DOM events, but also to apply user-defined events between components;

    <!--Parent component template-->
    <div id="app">
    //Hump identification needs to be converted
    <cpn @itemclick = "cpnClick"></cpn>
    </div>
    <template id="cpn">
    <div>
      <button v-for = "item in categories" @click = "btnClick(item)">
          {{item.name}}
      </button>
    </div>
    </template>
    <script>
    //Subcomponents
    	const cpn = {
      template:"#cpn",
      data(){
          return{
              categories:[
                  {id:'aaa',name:"Popular recommendation"},
                  {id:'bbb',name:"Mobile digital"},
                  {id:'ccc',name:"Computer office"}
              ]
          }
      },
      methods:{
          btnClick(item){
              //Pass the data of child components to parent components through custom events
             // Parameters are user-defined event name and self determining cause 
              this.$emit("itemclick",item)
          }
      }
    }
    //Parent component
    const app = new Vue({
      el:"#app",
      data:{
    
      },
      components:{
          cpn
      },
      methods:{
          cpnClick(item){
              console.log(item)
          }
      }
    })
    </script>
    

    Component module separation writing method

    - in the process of component development, because the writing method of the template module is too cumbersome, we can separate the HTML tags and write them, and then mount them on the corresponding components to make the structure clear;

    - there are two implementation schemes:

    1. Use the < script > tag. Note that the type must be x-template;
    2. Use the template tag;
    <!--1.use script label-->
    <script type = "text/x-template" id = "cpn">
    <div>
    	<h2>I'm the title</h2>    
    </div>
    </script>
    <!--2.use template label-->
    <template id="cpn">
    	<div>
    		<h2>I'm the title</h2>    
    	</div>
    </template>
    <script>
    	Vue.component('cpn',{
            template:'#cpn'
        })
    </script>
    
  3. Component data function

    - component is the encapsulation of a single functional module: This module has its own HTML module and its own attribute data;

    - the component cannot directly access the data in the Vue instance. Even if it can access it, put all the data in the Vue instance, and the Vue instance will become very bloated; Therefore, Vue components should have their own place to save data.

    - the component object also has a data attribute (in addition, it also contains other attributes like methods), but the data attribute must be a function, which returns an object with data stored inside;

    - why the data function can play a role of scope to prevent data calls between components. When creating components, it is necessary to re create and return objects, and the data between components will not affect each other;

    <template id="cpn">
    	<div>
         <h2>Current count:{{counter}}</h2> 
         <button @click="increment">+</button>
         <button @click="decrement">-</button>
      <div>
    </template>
    <script>
    	//Register components
     Vue.component('cpn',{
         template:'#cpn',
         data(){
             return {
                 counter:0
             }
         },
         methods:{
             increment(){
                 this.counter++
             },
             decrement(){
                 this.counter--
             }
         }
     })
    </script>
    

Tags: Front-end Vue

Posted on Sun, 28 Nov 2021 08:33:33 -0500 by shage