“This is the 25th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

13. New es6 features

Var, let, const

  • Var function: Use this keyword to declare that a variable is a global variable, which may cause variable confusion.
  • Let declares a local variable. Scope: Starts with a definition and ends with a newly defined block of code. [Recommended]
  • Const defines a constant. Function: A variable cannot be modified once defined. Special note: The value of a variable cannot be modified when modifying number or string. The address of an object cannot be modified when modifying an object.
<script >
     function test(){
        for(let i = 0; i < 10; i++){
            console.log("function inner:",i);
        }
        //console.log("function out:",i);
        const name = "xiaochen"; / / constant

        const user = {name:"Little three"}; // Const modifies an object. The address of the object cannot be changed
        console.log(user.name);
        user.name = "Xiao Ming";
        console.log(user.name);
    }
    test(); // Call the function
</script>
Copy the code

String templates use string templates with backquotes

    let html = "<div>\n"+
                    "

I am the tag

\n"
+ "<input type=\"text\" name=\"name\">\n"+ \n"+ "</div>\n"; let html1 = ` < div > < h1 > tag I am < / h1 > < input type = "text" name = "name" > < button > I am button < / button > < / div > `; console.log(html); console.log(html1); Copy the code

3, es6 function () {}

Anonymous functions have their own this, simplified as ()=>(arrow function), arrow functions have no this.

4. Object definition method

Es5 object definition:

let name = "Chen";
let age = 23;
let bir = "2012-12-12";
const user = {name:name,age:age,bir:bir} ; //es5
console.log(user);
Copy the code

Object extension in ES6: If the object attribute name is the same as the attribute assignment name, you can omit the variable name.

let name = "Chen";
let age = 23;
let bir = "2012-12-12";
const stu = {name,age,bir} ; //es6
console.log(stu);
Copy the code

14. Components in Vue

14.1. Vue standard development mode

1, VUE recommended development method is sPA: Single Page (Web)Application

  • Vue recommended development mode is based on single-page application single-page Web application

2. What is sPA single page application

  • Single-page application: a future project with only one page

3. Why does VUE recommend the development mode of sPA?

  1. Import vue JS files
  2. Only one VUE instance can exist on a page.

== The recommended vUE development mode requires that only one VUE instance == exist in an application

4. There are problems in using existing means to strictly follow sPA?

  1. Existing development methods result in more and more code in a single page in a project that is not conducive to subsequent maintenance

  2. The existing development mode leads to the completion of all business functions in the only page in the project, resulting in a very slow loading speed of the current page

5. Vue component is provided in VUE in order to strictly follow sPa development mode

Components:

  1. Component reduces the amount of vUE root instance code
  2. A group completes a function or group of work in a project to achieve business function isolation
  3. Components can also be reused in VUE

14.2. Functions of Components

Component functions: Used to reduce the amount of code in the Vue instance object. In the future, in the process of using Vue, the page can be divided into different components according to different business functions, and then the layout of the whole page can be completed by multiple components, which is convenient for the page management when using Vue for development in the future, and convenient for developers to maintain. Components can also be shared and reused.

14.3 use of components

14.3.1 Global Component Registration

Note: A global component is registered with a Vue instance and can later be used within the scope of any Vue instance

//1. Develop global components
<script>
    // Develop global components
    Component name Parameter 2: Specifies the configuration object of the component content
    Vue.component('login', {template:"
      

User login component

"
.Note: The template property must have a root container, one and only }); Vue.component('register', {template: "

User registration component

"
}); const app = new Vue({ el: "#app".data:{ }, methods:{ }, computed: {}}); </script>//2. Use global components within the scope of Vue instances <div id="app"> <! -- Use global components: Use global components by component name --> <login></login> <register></register> </div> Copy the code
# Note: -1.Vue.com Ponent is used to develop global component parameters1: Component name parameter2Component configuration {} template:' 'The TEMPLATE HTML code used to write the component must have one and only root element -2.You need to use the global component - based on the component name within the scope of the Vue3.If you use a hump name during the component registration process, you must lowercase all the words for the hump in the - line to useCopy the code

14.3.2. Local Component Registration

Note: Components are registered by registering them with a component property in the corresponding Vue instance. This method does not accumulate Vue instances

  • The first type of development
// Local component login template declaration
// Define the login component configuration object
const login = {  // Define a login component
    template:"
      

User login local component

"
} const app = new Vue({ el: "#app".data:{ }, methods:{ }, computed:{ }, components: {// Components registered here are local components login, //es5 login:login es6 login, register: {template:"

User registration local component

"
}}});// Local components are used within the scope of Vue instances <login></login> <register></register> Copy the code
  • Second development mode
//1. Declare the local component template tag. Note: Declare it outside the scope of the Vue instance
    <template id="loginTemplate">
        <div>
            <h3>Users log in to local components</h3>
            <input type="text">
        </div>
    </template>

//2. Define variables to save template configuration objects
    // Define the login component configuration object
    const login = {  // Define a login component
        template:"#loginTemplate"
    };

//3. Register components
    const app = new Vue({
        el: "#app".data:{
        },
        methods:{
        },
        computed:{
        },
        components: {// Components registered here are local components
            login,   // Register the login component}});//4. Local components are used within the scope of Vue instances
	<login></login>
Copy the code

14.4. Use of Prop

Function :props is used to pass static or dynamic data to a component

14.4.1. Pass static data internally to a component by declaring it on it

//1. Declare the component template configuration object
      const login = {
        template: "< div > < h3 > login interface - {{title}} {{count}} - {{age}} < / h3 > < / div >".data(){ // Note: Data is defined in props, and cannot be repeated in data. If multiple definitions are used, the data in props is preferred
            return {
                loginTitle : this.title,
            };
        },
        props: ['title'.'count'.'age'].// the props function is used to receive data passed through the component label when using the component
    };

//2. Register components
// How do I implement the parent component to pass data internally to the child component and display the data in the child component? Note: In VUE the parent component passes data to the child component using the prop property
    const app = new Vue({
       el:"#app".data: {msg: "Component development in Vue",},methods: {},computed: {},components:{
            login, // Register group price}});//3. Complete data transfer through components
	<login title="Welcome to our system!!" count="11" age="23"></login>
Copy the code
# summary:1.When using a component, you can define multiple properties and corresponding data on the component2.Multiple property names defined on the component can be used inside the component using the props array. Property values in the component can later be obtained by {{property name}} in the component3.Data is defined in props, and cannot be repeated in data. If multiple definitions are used, data in props is preferredCopy the code

14.4.2. Pass dynamic data internally to a component by declaring it on it

//1. Declare the component template object
    const login = {
        template: 
      

Login interface -{{title}}

"
.data(){ return{}; },props: ['title'].// the props function is used to receive data passed through the component label when using the component }; //2. Register local components const app = new Vue({ el:"#app".data: {msg: "Component development in Vue".name:"Xiao li",},methods: {},computed: {},components:{ login, // Register group price}});//3. Use components <login :title="name"></login> // Use v-bind to bind the data attribute in the Vue instance. If the data attribute changes in the future, the internal data of the component changes accordingly Copy the code

14.4.3 Unidirectional data flow of PROP

One-way data flow: All prop forms a one-way downlink binding between their parent prop: updates to the parent prop flow down to the child, but not the other way around.

  • All prop forms a one-way downlink binding between their parent prop: updates to the parent prop flow down to the child, but not the other way around. This prevents accidental changes in the state of the parent component from the child, which can make the data flow of your application difficult to understand.

  • Additionally, every time the parent component is updated, all prop in the child component will be refreshed to the latest value. This means that you should not change a prop inside a child component. If you do, Vue will issue a warning in the browser console. — From the official website

14.5. Define data and event usage in components

14.5.1. Components define data belonging to components
// Define a local user list component configuration object
const users = {
    template:"
      

User list -{{count}}-{{name}}

"
.// Used to define the component's HTML content data(){ Note: Data defined in a component is only available in the current component return { count:0.name:"Xiao li"}; }};Copy the code
14.5.2. Event definitions in components
// Define a local user list component configuration object
const users = {
    template:"< div > < h3 > user list - {{count}} {{name}} - {{countSqrt}} < / h3 > < button @ click = 'changeCount' > + < / button > < ul > < li v - for = 'item in items'>{{item}}".// Used to define the component's HTML content
    data(){     Note: Data defined in a component is only available in the current component
        return {
            count:0.name:"Xiao li".//items:[" Shanxi "," Beijing "," Tianjin "],
            items:[],
        };
    },
    methods: {// Used to define a sequence of events for the current component
        changeCount(){
            this.count++; }},computed: {// It is used to define a set of calculated properties for the current component, which are used to perform secondary calculations on the results of the page
        countSqrt(){
            return this.count*this.count; }},created(){ // The component has injected data, methods, computed related data methods
        // Send the request
        /*axios.get("/xxx").then(res=>{ this.items = res.data; }); * /
        this.items=["Shanxi"."Beijing"."Tianjin"]; }};Copy the code
# summary1.Defining an event in a component is almost the same as defining an event in a Vue by adding @event name = function name to the corresponding HTML code inside the component2.Use the methods attribute inside the component to define the corresponding event functionthisPoints to an instance of the current componentCopy the code

14.6. Pass an event to a child component and call the event in a child component

Calls to related events passed from a child component must be called using this.$emit(‘ function name ‘)

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue series of courses</title>
</head>
<body>
    <div id="app">
       <h1>Info: {{MSG}} Age: {{age}}</h1>

       <login @aa="findAll" @test="test"></login>
    </div>
</body>
</html>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
    // How to pass an event from a parent component to a child component 1. Use @ alias = "Pass event name" 2. This.$emit(' alias ') when the event passed is called in the component

    // Define a login component configuration object
    const login = {
        template: "< div > < h3 > user login - {{MSG}} < / h3 > < button @ click = 'test' > point I triggering event < / button > < / div >".data(){
            return {
                msg:"I am the information of the child component".age:23.user: {id:2.name:"Chen".age:23.bir:"2012-02-09"}}; },methods: {test(){
                alert('Events defined in the child component... ');
                // Call the parent component findAll aa event name:
               // this.$emit('aa'); $emit is used to call related events in the parent component
                this.$emit('test'.this.msg,this.age,this.user);   //$emit is used to call related events in the parent component and pass parameters}}};const app = new Vue({
       el:"#app".data: {msg: "Component development in Vue".age:23.user: {id:1.name:"Xiao wu".age:12}},methods: {findAll(){
               alert('Events defined in the parent component... ');
           },
           test(msg,age,user) {
               alert('Event that defines test in parent component.... '+msg);
               console.log("msg:",msg);
               console.log("age",age);
               console.log("user",user);
               this.msg = msg;
               this.age = age; }},computed: {},components:{
            login, // Register the component}});</script>
Copy the code

14.7. Use of slots

What about slots?

  • Slot is equivalent to an empty tag. Vue allows you to dynamically change values and styles, and to extract a block of content for reuse, just as Java encapsulates utility classes.

  • A slot is a placeholder in a child component that is provided to the parent component.

  • In the process of building a page, we usually extract the most common parts as a separate component, but in the actual use of this component can not fully meet the requirements, I want to add something to this component, when we need to use slots to distribute content.

  • Slot is a slot in which a new DOM element is automatically filled when a child component uses the child component label

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue series of courses</title>
</head>
<body>
    <div id="app">
       <h1>{{msg}}</h1>
        <! -- Vue uses components -->
       <login><h5 slot="aa">I am user - defined AA content</h5><h5 slot="bb">I am user - defined BB content</h5></login>
        <hr>
        <login><button>+++</button></login>
        <hr>
        <login></login>
        <hr>
    </div>
</body>
</html>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>//slot: slot: used to extend custom components to make components more flexible and to personalize their own components note: slots must work with components to use const login = {template:"<div><slot name='aa'><span>The default extension</span></slot><h3>User login interface</h3><slot name='bb'><span>The default extension</span></slot></div>"}; Const app = new Vue({el:"#app", data:{MSG :" Slot slot usage "}, methods:{}, computed:{}, components: {login,},});</script>
Copy the code

15. Vue Router

15.1, routing,

Routing: according to the path of the request according to certain routing rules for request forwarding so as to help us achieve unified request management

15.2,

Used to dynamically switch between components in vUE

15.3. Using Routes

1. Import routes

<! - the CDN way -- -- ><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>  / / the vue routing js<! -- local import --><script src="js/vue-router.js"></script>
Copy the code

2. Create a component object

// Create a component configuration object
const users = {
    template:"
      

User management

"
}; const emps = { template:

Employee management

"
} Copy the code

3. Define rules for routing objects

const router = new VueRouter({
    routes:[
        {path:'/users'.component:users}, Path: specifies the request path. Component: specifies the component to which the path corresponds
        {path:'/emps'.component:emps }  // To define some rules]});Copy the code

4. Register the routing object with the VUE instance

const app = new Vue({
    el:"#app".data: {msg:"Use of router in VUE",},methods: {},computed: {},components: {},// Registry component
    router:router,  // To register the routing configuration
});
Copy the code

5. Display the routing components on the page

<! The router-view tag is used to display the router component's location.
<router-view></router-view>
Copy the code

5. Switch routes based on links

<a href="#/users">User management</a>
<a href="#/emps">Staff management</a>
Copy the code

15.4 router-link Use

Purpose: To replace the use of a label when switching routes

Benefits: You can automatically add routes to paths

<! Add # to: used to specify the routing path tag: used to specify the router-link underlying render tag -->
<router-link to="/users" tag="a">User Management (link)</router-link>
<router-link to="/emps"  tag="a">Staff Management (Link)</router-link>
Copy the code
# summary:
1. Router-link is used to replace tag A to implement route switchover. The advantage is that the route path is directly written without #Copy the code

15.5. Default Route

What it does: Displays a default component on first entry

const router = new VueRouter({
    routes: [//{ path:'/',component:login},
        {path:'/'.redirect:'users' },     // default route rules redirect:(route path redirection)
        {path:'/users'.component:users},  // User component routing rules
        {path:'/emps'.component:emps }   // Employee component routing rules]});Copy the code

15.6 Two modes of dynamic route switchover

Method 1: Switch routes using labels

<! --1.Switch routes using labels --><a href="#/users">User management</a>
<a href="#/emps">Staff management</a>
<router-link to="/users" tag="a">User Management (link)</router-link>
<router-link to="/emps"  tag="a">Staff Management (Link)</router-link>
Copy the code

Method 2: Use JS code to dynamically switch routes

<! --2.Dynamic route switching through JS codethis.router.push("Switched routing path") -- - ><button @click="test">Testing dynamic Routing</button>

const app = new Vue({
    el:"#app".data: {msg:"Use of router in VUE use of route-link tag",},methods: {test(){
            console.log("test");
            //this.$router.push("/emps"); // Indicates to switch the routing path
            //this.$router.push({path:'/emps'}); // Switch routes
            this.$router.push({name:"emps"}); // Name mode Switch route [recommended]}},computed: {},components: {},// Registry component
    router,     // Register the route
});
Copy the code

15.7. Parameter transfer in Routing

The first way to pass parameters is the traditional way

1. Pass? Concatenation parameter in sign form

<! --1.Access to? Post pass parameterthis.route.query.key.? Key --><router-link to="/users? Deptid = 21 & name = li si">User management</router-link>
Copy the code

2. Get parameters from the component

const users = {
    template:"
      

User management

"
.data(){ return {}; }, methods: {}, created(){ 1. Obtain the parameters in queryString(deptid=21) //this.$route Specifies the current route object //this.$router Router object console.log("deptid:".this.$route.query.deptid); console.log("name:".this.$route.query.name); }};Copy the code

The second way to pass parameters is restful

1. Pass parameters by using paths

<! --2.Obtain parameters in routing paths. Obtain parameters in REST modethis$route.params. alias in path --><router-link to="/ emps / 11 / fifty">Staff management</router-link>
const router = new VueRouter({
    routes:[      
        {path:'/emps/:id/:name'.name:'emps'.component:emps }   // Employee component routing rules]});Copy the code

2. Get parameters from the component

const emps = {
    template: "
      

Staff management

"
.data(){ return {}; }, methods: {}, created() { console.log("id:".this.$route.params.id); // Get the parameters in the path console.log("name:".this.$route.params.name); // Get the parameters in the path}}Copy the code

The complete code

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue series of courses</title>
</head>
<body>
    <div id="app">
        <h1>{{msg}}</h1>

        <! -- Switch routes -->
        <! - 1. To get? This.route.query.key.? Key -->
        <router-link to="/users? Deptid = 21 & name = li si">User management</router-link>
        <! --2. Obtain the route path parameter rest method parameter this.$route.params. Alias in path -->
        <router-link to="/ emps / 11 / fifty">Staff management</router-link>

        <! --router-view displays routing components -->
        <router-view></router-view>

    </div>
</body>
</html>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script src="js/vue-router.js"></script>
<script>

    // Create a component configuration object
    const users = {
        template:"
       

User management

"
.data(){ return {}; }, methods: {}, created(){ 1. Obtain the parameters in queryString(deptid=21) //this.$route Specifies the current route object //this.$router Router object console.log("deptid:".this.$route.query.deptid); console.log("name:".this.$route.query.name); }};const emps = { template: "

Staff management

"
.data(){ return {}; }, methods: {}, created() { console.log("id:".this.$route.params.id); // Get the parameters in the path console.log("name:".this.$route.params.name); // Get the parameters in the path}}// Create routing objects and define routing rules const router = new VueRouter({ routes:[ {path:'/'.redirect:'users' }, // default route rules redirect:(route path redirection) {path:'/users'.name:'users'.component:users}, // User component routing rule Name: The route name must be unique {path:'/emps/:id/:name'.name:'emps'.component:emps } // Employee component routing rules]});const app = new Vue({ el:"#app".data: {msg:"Use of router in VUE use of route-link tag",},methods:{ }, computed: {},components: {},// Registry component router, // Register the route });
</script> Copy the code

15.8. Nested set by

1. Declare the outermost and inner routes

<template id="product">
    <div>
        <h1>Commodity management</h1>

        <router-link to="/product/add">Goods to add</router-link>
        <router-link to="/product/edit">Commodities editor</router-link>

        <router-view></router-view>

    </div>
</template>

// Declare the component template
const product={
  template:'#product'
};

const add = {
  template:'

Merchandise added

'
}; const edit = { template:'

Merchandise editor

'
}; Copy the code

2. Create a routing object containing nested routes

const router = new VueRouter({
        routes:[
            {
                path:'/product'.component:product,
                children:[
                    {path:'add'.component: add},
                    {path:'edit'.component: edit},
                ]
            },
        ]
    });
Copy the code

3. Register the routing object

const app = new Vue({
    el: "#app".data: {},
    methods: {},
    router,// Define the routing object
});
Copy the code

4. Test the route

<router-link to="/product">Commodity management</router-link>
<router-view></router-view>
Copy the code

Case exercises:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue series of courses</title>
</head>
<body>
    <div id="app">
        <h1>{{msg}}</h1>

        <! -- Routing link -->
        <router-link to="/products">Commodity management</router-link>
        <! -- Display routing components -->
        <router-view></router-view>
    </div>
</body>
</html>
<template id="productsTemplate">
    <div>
        <div><h3>List of goods</h3></div>
        <a href="#/products/add">Adding product Information</a>
        <table border="1">
            <tr>
                <th>Serial number</th>
                <th>The name of the</th>
                <th>The price</th>
                <th>The date of production</th>
                <th>operation</th>
            </tr>
            <tr>
                <td>1</td>
                <td>With short sleeves</td>
                <td>60.88</td>
                <td>2021-06-09</td>
                <! -- < th > < a href = "" > delete < / a > < a href =" # / products/edit "> change < / a > < / th > -- >
                <td><a href="">delete</a><a href="javascript:;" @click.prevent="EditRow ({id: 1, name: 'Chen'})">Modify the</a></td>
            </tr>
        </table>
        <! -- Router-view displays child routing components -->
        <router-view></router-view>
    </div>

</template>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script src="js/vue-router.js"></script>
<script>

    // Create a component configuration object
    const products = {
        template:"#productsTemplate".data(){
            return {};
        },
        methods: {editRow(user){
                console.log(user);
                this.$router.push({path:'/products/edit'.query:user}); // Switch the routing path through query(?)}}};// Create the add item information subcomponent
    const add = {
        template: "
       


"
} const edit = { template: "


"
.data() { return { user: {}}; },methods: {},created(){ console.log("edit: ".this.$route.query); this.user = this.$route.query; }}// Create a routing object const router = new VueRouter({ routes:[ {path:'/'.redirect:'/products' }, // Default route { path:'/products'.name:'products'.component:products, children: [// Define child routes Note: The path attribute of child routes cannot start with a '/' {path:"add".component:add}, {path:"edit".component:edit}, ] }, ] }); const app = new Vue({ el:"#app".data: {msg:"Use of nested routines in router in Vue",},methods: {},computed: {},components:{ products, }, router, // Register the route });
</script> Copy the code

Run screenshot: