A week of Vue proficiency

Keywords: Front-end Vue Attribute Python network

new Vue (el, data, methods, computed, filters, components, life cycle functions)

  • el:

    Mount page elements
  • data:

    data
  • methods:

    Define Functions
  • computed:

    Calculate Attributes This defines a method but is typically called as a variable
     This method loop, which is more efficient than the methods of methods, is called each time and there will be a cache that will only be called once
  • filters:

    Define filter functions
  • components:

    Local component registration
    
    

vue's life cycle (create->die)

  • beforeCreate
  • created:

    Normally network requests are made here
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • beforeDestroy
  • destroyed

Template syntax

  • Interpolation syntax:

    Not only variables but also expressions can be written in {{massage}} {{}}
    

vue directive

Interpolation instructions

  • v-once:

    An instruction without = "" content can only be assigned once and will not change when the data changes
  • v-html:

    Load data according to html syntax
  • v-text:

    Load data into a label and overwrite everything inside the label
  • v-pre:

    Presenting everything as it is can invalidate template interpolation syntax similar to python's original string
  • v-cloak:

    This property is similar to display:none vue does not parse to show that the template has this property before vue parsing and then deletes it after parsing

Dynamic Binding Instructions

  • v-bind:
    Dynamic binding properties (v-bind:src) can be abbreviated as (:src) Any property can be used: src=''content supports variables, arrays, objects, methods, and expressions
  • v-on:
    Binding events (v-on:click) can be abbreviated as (@click) supporting all events

    • $event:

      @click (prm, $event) $event default write receives browser-generated event objects
    • stop modifier:

      @click.stop prevents event bubbles
    • prevent modifier:

      @click.prevent prevents submit submissions
    • Keyboard modifier:

      @keyup.enter listens for carriage return build event action enter indicates that you can change to another key here 
    • once modifier:

      The @click.once event can only be triggered once This is a good place to prevent duplicate submissions
  • v-for:
    Loop operation if only one value is accepted when traversing an object defaults to value

    • key property of component

      You can optionally bind a key in a loop but try not to bind index because of index
       Is each change If a value is inserted into the list, all index es are reordered to make changes
       The data inside the bound item is not affected by sorting, so the performance is better In general, the key binds a unique value
      
  • v-if:
    Fast rendering code when conditions are met
  • v-else:
    else code block
  • v-else-if:
    Fast rendering code when conditions are met
  • v-show:
    Show the code block when the condition is true Otherwise hide the code block and display:none are the same and v-if is not created directly DOM There will always be DOM but not shown
  • Vue.set (object to modify, index value, value to modify)
  • v-model:
    Bidirectional bindings are used to synchronize updates to the value property by default

    • lazy modifier:

      Lazy loading does not bind updates in real time to both directions. Updates are only made when the user returns or unlocks the focus.
    • number modifier:

      By default, data bound in both directions is all string types Here you can specify the type of binding
    • trim modifier:

      Automatically removes spaces on both sides of a string
<h2>{{message}}</h2>
<!--v-model Binding in both directions-->
<input type="text" v-model="message">

<!--Bidirectional binding can also be implemented in another way-->
<input type="text" :value="message" :input="valueChange">
<script >
function valueChange(event){
    console.log("When the content of the input box is changed input Time Trigger, Produced by browser event To get input content");
    this.message = event.target.value;
}
</script>
<!--Abbreviation-->
<input type="text" :value="message" @input="message=$event.target.value">

Virtual DOM

Rendering

  • key rendering

    Determine whether vue will reload the DOM when updating the DOM through the key attribute of the tag
     If the key s are the same, you can take the DOM without reloading it, but the attribute data of the DOM changes
     Reload a new DOM directly if it is not the same
  • Response of vue

    Not all modifications are responsive, such as List operations if a list.push("hello") page is used
     If list[0] ='hello'is used, the data has changed but the page will not be modified responsively
    

ES6

Array method

  • push method
    Insert a value to the last list
  • pop method
    Remove the last value from the list
  • shift method
    Remove the first element from the list and delete it
  • unshift method
    Insert a value before the list
  • splice method

    • Delete element

      If the first parameter of the element to be deleted is passed in from the first parameter to the second parameter, you will delete several elements
       If only the first element is passed, delete all elements after the subscript of the first parameter
    • Insert Element

      The first parameter representing the start element The second parameter defaults to 0 The third parameter after is the parameter to insert
    • Replace Element

      The first represents the start of the parameter, the second represents the end, and the third after represents the inserted parameter
  • sort method
    Sort list s
  • reverse method
    Invert list
  • Advanced String
    ``Line breaks are recognized

function

  • function abbreviation
add: function() {}
// Can be overridden to 
add(){}
  • function indefinite length parameter
   add(...param){}
   // ... indicates that a variable-length parameter is acceptable and param is of list type at this time  
   // def add(*param) similar to python
  • for loop
// Ordinary for loop
for (let i = 0; i < 10; i++){
    console.log(list[i]);
}
// Index for loop
for (let i in [1, 2, 3]){
    console.log(list[i])
}
// Enhance for cycle
for (let item of [1, 2, 3]){
    console.log(item)
}
  • Higher order function
// filter function
const numList = [10, 20, 100, 21, 50, 20, 332, 213, 2123];
let newList = numList.filter(function(n){
  return n >= 50
});
// map function
let new2List = newList.map(function(n) {
  return n * 2
});
// The reduce function summarizes everything in the array The first parameter is the callback function The second parameter is the initialized value
let totalCount = new2List.reduce(function(preValue, n){
// Initialization preValue is the value n initialized by higher-order functions is an element in the list 
// Each callback assigns the return ed result to preValue
  return preValue + n
}, 0);
  • Arrow function
const numList = [10, 20, 100, 21, 50, 20, 332, 213, 2123];
let total = numList.filter(n => n <= 50).map(n => n * 2).reduce((pre, n) => pre + n, 0);
console.log(total);

Componentization

  • Basic Use

    • Global Components Global Components indicate registered components can be used anywhere
    • Local components created by local components can only be used inside mounted elements
// Create Component Constructor (Sub-Component)
const cpn1 = Vue.extend({
    template: `
            <div>
                <h2>cpn1 Title</h2>
                <p>cpn1 content</p>
            </div>
            `
});

// Create Component Constructor (Parent Component)
const cpn = Vue.extend({
    // ``is an advanced string that can wrap lines
    template: `
            <div>
                <h2>cpn Title</h2>
                <p>cpn content</p>
                <cpn1></cpn1>
            </div>
            `,
    // Here you can register other components within the component constructor This registered component can be used within a template
    components: {
        cpn1: cpn1
    }
});

// Register Global Components
Vue.component('my-dev', cpn);

// Registering a local component vm can be seen as a root component
const vm = new Vue({
    el: '#app',
    data: {},
    methods:{},
    // Register local components
    component:{
        cpn: cpn
}
});


// Using Components
// <my-dev></my-dev>
  • Component Registration Syntax Sugar

    • Registration can directly omit extend s and directly replace them with objects
Vue.component('cpn1', {
    template: `
        <div>
            <h2>cpn1 Title</h2>
            <p>cpn1 content</p>
        </div>
        `
});
  • Template Separation Writing

<!--adopt id  Make a selector for template Attribute assignment substitution template A string that looks uncomfortable in-->

<script type="text/x-template" id="cpn">
    <h3>Title</h3>
    <p>Content.</p>
</script>

<template id="cpn2">
    <h1>Title</h1>
</template>
<script>
    Vue.component('my-cpn', {
        template: "#cpn"
    });
</script>
  • Component Content Access Vue Instance Data
    Data content within the Vue instance is not directly accessible within the default component
    There will be a data property inside the component and this data property must be a function that returns an object that holds the data inside

    • Why must data within a component be a function?

      Because the data that the component applies when reusing is an object, then each reference is the same object, when this
       When an object changes, all places where the data is used are modified by a linkage, so you need to return an object with a function, which means every time
       The reuse component calls the data function once to get a new data object so that it can be isolated from each other, which is similar to the relationship between deep and shallow copies.
      

Communication between components

  • Usage of props (parent passed to child)

    • props supported data types
    1. String
    2. Number
    3. Boolean
    4. Array
    5. Object
    6. Date
    7. Function
    8. Symbol
    • Note: A root component is required when defining a detach template and cannot be parsed properly without a root component
<!--Subcomponent Template-->
<template id="cpn">
    <div>
        <p>{{c_movies}}</p>
        <h2>{{c_message}}</h2>
        <ul>
            <li v-for="item in c_movies"> {{item}}</li>
        </ul>
    </div>

</template>



<!--Parent Component Template-->
<div id="app">
    <!--    props Data Binds data from parent components in both directions-->
    <cpn :c_movies="movies" :c_message="message"></cpn>
</div>

<script>

    // Subcomponents
    const cpn = {
        template: "#cpn",
        // The parent component passes data to the child component 
        // First Array Method
        // props: ['c_movies', 'c_message'],

        // Second way of object
        props: {
            // 1. Type Restrictions
            // c_movies: Array,
            // c_message: String,

            // 2. Provide some default values
            c_message: {
                // data type
                type: String,
                // Default value
                default: 'This is message data',
                // Is the parameter required
                required: true,
            },
            c_movies: {
                type: Array,
                default: []
            }
        },
        data() {
            return {}
        }
    };

    // Parent Component
    const vm = new Vue({
        el: "#app",
        data: {
            message: 'information',
            movies: ['dominant sea power', 'One Piece', 'Remembering the Remaining Year', 'Myth']
        },
        components: {
            cpn: cpn
        }
    });

</script>
  • this.$emit usage (child components pass events to parent components)
<!--Subcomponent Template-->
<template id="cpn">
    <div>
        <button v-for="item in categories" @click="bthClick(item)">
            {{item.name}}
        </button>
    </div>
</template>

<!--Parent Component Template-->
<div id="app">
    <!--Listen for subcomponent events-->
    <!--If the parent component's method If not transmitted item Then the default is item No event-->
    <cpn @item_click="cpn_click"></cpn>
</div>

<script>

    // Subcomponents
    const cpn = {
        template: "#cpn",
        data() {
            return {
                categories: [
                    {id: '1', name: 'Popular Recommendations'},
                    {id: '2', name: 'Mobile phone digital'},
                    {id: '3', name: 'Household Appliances'},
                    {id: '4', name: 'Computer Office'},
                    {id: '5', name: 'Daily use'},
                ]
            }
        },
        methods: {
            bthClick(item) {
                console.log(item);
                // Send custom events from child components to parent components to pass item parameters
                this.$emit("item_click", item)
            }
        }
    };

    // Parent Component
    const vm = new Vue({
        el: "#app",
        data: [],
        components: {
            cpn
        },
        methods: {
            // Accept item parameters
            cpn_click(item) {
                console.log('Listened for events from subcomponents!');
                console.log(item);
            }
        }
    });


</script>

Posted by lindm on Sun, 22 Dec 2019 18:34:53 -0800