4D replay Vue2 related knowledge (suitable for friends who have learned but forgot but need to get started)

foreword

This is a blog to help readers quickly review the practical knowledge points of Vue2.

Let me talk about the author's situation first. One month before writing this article, I just helped my teacher finish his company's official website. This is a display website. After two days of writing, the content is basically finished.

During this month, I did not touch the relevant content of Vue2, but reviewed the relevant content related to the front-end request. So I was asked to change this website a month later, and I was confused when I looked at the code. So I want to spend an afternoon reviewing the content related to Vue2 practice.

Note: This article is aimed at a situation similar to mine. I have learned Vue2 systematically before but have forgotten friends because I haven’t touched them for a long time. The purpose is not to relearn, but toreview. Therefore, I will take a lot of content in one stroke, and I will explain the key content in detail. I hope readers understand.

Finally, let me talk about the general content of this article, which is divided into the following sections:Scaffolding creates a vue project and its basic configuration, the basic part of vue, important life cycle functions, component programming, information transfer between components, and vue routing

Of course, this is not a simple review article, and it will contain a lot of my experience in doing projects. Hope to help you! !

First, the creation and basic configuration of the Vue2 project

1.1 Create a project with scaffolding

Select the appropriate folder, open the terminal, and enter the command line statement:

Vue create 文件名

Just select the appropriate configuration.

1.2 Project structure

insert image description here
The picture above is the structure of an initial vue2 project created with scaffolding. It needs to be understood that the code written by oneself is placed inside src, assets store pictures, components store components, main.js is the entry file, and App.vue can be understood as the component initially rendered by the project.

1.3 Entry file main.js

The initial configuration of main.js is fixed.

First, import the Vue file

import Vue from 'vue'

Next, import App.vue

import App from './App.vue'

Then, create an instance object of Vue. Vue is essentially a constructor, so we create an instance object of the Vue constructor

new Vue({
    
    
	el: '#app',
	render: h => h(App)
})

There is another way of writing, which is also the way scaffolding gave us:

new Vue({
    
    
	render: h => h(App)
}).$mount('#app')

Here is a brief explanation of why render is needed. The function of render is to make up for the template parsing function of the incomplete version of Vue. render is a function, and the parameter is an h function. == The function is to put the content of the App into the initial page. == With this step, after we open the project, what we see is the content in the App component.

1.4 Component configuration

Here I want to talk about the basic configuration of the App component.

<template>
  <div></div>
</template>

<script>
export default {
    
    
  name: 'App',
  data() {
    
    
  	return {
    
    }
  }
}
</script>

<style scoped>

</style>

In general, the components in the Vue2 project will be presented in the above format. Among them, there needs to be a div inside the template, and this div is also called the root node. In the components of Vue2, there must be a root node (not used in Vue3).

Then there is name, each component can have a component name, which will be used in routing rules.

The last is data, the data in data must be written in this form in vue2. Data is divided into function form and object form. If it is written in object form in Vue, multiple components will use data, and the data will be changed. A change to data in one component will affect the data in all components, so the function form must be used to write data

Finally, mention the scoped in the style. The existence of scoped is that if there is a class called box in the content of component A and component B, if there is no scoped, the class name is the same in a project, and the element styles will affect each other. If scoped exists, there will be no such problems. The style of each component is independent and will not be affected by other components.

1.4 Running the project

open terminal

npm run serve

If you want to package the project

npm run build

Of course, the command statements under these knowledge scaffolds can be changed but need to be configured. The statements of some vue2 templates are also different, usually the following is also more commonly used:

npm run dev

Two, the basic knowledge of Vue

The contents covered in this section are: data display, data binding, event processing, loop traversal, judgment syntax, calculated properties, and monitoring properties.

Remind again, due to the large content, so many places have been mentioned in one stroke!

2.1 Data display

According to the data, three are introduced here, namely v-text, v-html and interpolation syntax.

Instruction format:

<div v-text='123'></div>
<div v-html="<h1>123</h1>"></div>

Note that v-html should be used sparingly, and it is especially taboo to place a link. Easy to cause XSS attack

The more important thing is the interpolation syntax, please see the following code:

<template>
  <div>
    <h1>个人信息</h1>
    name: {
    
    {
    
     person.name }}
    age: {
    
    {
    
     person.age }}
  </div>
</template>

<script>
export default {
    
    
  name: 'App',
  data() {
    
    
    return {
    
    
      person: {
    
    
        name: '巧克力小猫猿',
        age: 20
      }
    }
  }
}
</script>

In this code, the following is data, and the above uses the interpolation syntax to extract the following content.

What I want to say here is that in vue2, if you need to operate on data and get data, please see the following code:

<template>
  <div>
    <h1>个人信息</h1>
    name: {
    
    {
    
     person.name }}
    age: {
    
    {
    
     person.age }}
    <button @click="add">+1</button>
  </div>
</template>
<script>
export default {
    
    
  name: 'App',
  data() {
    
    
    return {
    
    
      person: {
    
    
        name: '巧克力小猫猿',
        age: 20
      }
    }
  },
  methods: {
    
    
    add() {
    
    
      this.person.age ++;
    }
  },
}
</script>

In the above code, the implementation is to add 1 to the age. First, the age must be obtained. In the interpolation syntax, the person.age is directly written, but in the function, the age needs to be obtained.Use this.

2.2 Data Binding

There are two types of data binding, one is one-way binding of data, and the other is two-way binding of data.

One-way binding: v-bind
Two-way binding: v-model

Starting from the form, please see the following code:

    <br>
    班级1: <input type="text" v-bind:value="person.class">
    班级2: <input type="text" v-model="person.class2">

insert image description here
final result:
insert image description here

Final result description: Since the form is bound one-way and two-way, the values ​​are all pre-set values. The difference is that for one-way binding, modifying the value data on the page cannot be synchronized, but modifying the data in the console below, the correct data can be rendered;

In the case of two-way binding, if the value is modified on the page, the data in data will change; if the data in data is changed, the value of the page will also change.

Two-way binding for forms, but one-way binding, that is, v-bind, has many uses besides forms, such as passing data between components (will be written later), such as reading js code in tags: one-way
insert image description here
binding The issues to be aware of are:One-way binding is used, and the js code is inside the quotation marks.

The last thing to say is that the shorthand for one-way binding, with a colon in front, is just like the previous picture.

2.3 Event Handling

Event processing is equivalent to native click, mouse pass, mouse leave and other events. After the event is triggered, there will be a callback function, which is called event processing in Vue.

Still the example just now, set a button, click the button to increase the age, just understand the abbreviation here:

    age: {
    
    {
    
     person.age }}
    <button @click="add">+1</button>

Here, the add event is actually bound to the button; the add event is written in methods:

  methods: {
    
    
    add() {
    
    
      this.person.age ++;
    }

The above is also the most used.

2.4 Loop Traversal

This is a very important point. And there are many key points.

First, an array is given in data:

      arr: [1, 2, 3, 4, 5]

Then start traversing.

It should be noted here that in vue, ul and li are generally used for traversal:

    <ul>
      <li v-for="a in arr" :key="a.id">{
    
    {
    
     a }}</li>
    </ul>

ul is fixed, as many pieces of data as there are, how many li will be automatically generated. There is a v-for in li, and v-for has two contents, a is a variable we customized to store our data, and arr is an array that needs to be traversed. a in arr means to traverse the array arr, and each piece of data is stored by the corresponding a.

Each data will automatically generate an id, which can be understood as the ID card of the data. This: key must be present, otherwise an error will be reported.

Since it is a review article, the principle is skipped. If you are interested, you can check the blog related to responsiveness to understand the principle. A special topic will be released later to record the principle part of Vue, so you can pay attention to it.

Use interpolation syntax to write the data we need in the content of li.

The final effect:
insert image description here

2.5 Judgment grammar

Judgment syntax is divided into v-if and v-show.

They can set whether the elements in the page can be seen according to certain judgment conditions. Among them, the principle of v-if is to display if the conditions are met, and delete the page structure if the conditions are not met; v-show is set according to display: none, just hides the page content, and the page structure still exists.

2.6 Computed properties

Computed properties are essentially functions.

Here we look at a name case, I will analyze it with code:

<template>
  <div class="box">
    姓氏: {
    
    {
    
     firstName }}
    <br>
    名字: {
    
    {
    
     lastName }}
    <br>
    合计: {
    
    {
    
     fullName }}
  </div>
</template>

<script>
export default {
    
    
  name: 'App',
  data() {
    
    
    return {
    
    
      firstName: '巧',
      lastName: '克力小猫猿',
    }
  },
  computed: {
    
    
    fullName() {
    
    
      return this.firstName + this.lastName
    }
  }
}
</script>

The above is the shorthand part for computed properties. The most used ones are actually abbreviations. Computed is a sign of a computed attribute, and the fullName function behind it processes the fullName. The interpolation syntax can be used directly in the page structure:
insert image description here
there will also be get and set in the complex version of the calculated property, which is omitted here for self-understanding.

2.7 Monitoring Properties

Here is also a concise version of the monitoring attribute. The monitoring attribute is very similar to the calculated attribute. This code is added on the basis of the previous one:

  watch: {
    
    
    fullName(newvalue, oldvalue) {
    
    
      console.log(newvalue)
      console.log(oldvalue)
    }
  }

The monitoring attribute has two parameters, one is newvalue and the other is oldvalue, which are the latest value of fullName and the old value respectively.
insert image description here

Three, important life cycle functions

If you don't understand the life cycle, you can learn about it. This section only talks about some important lifecycle functions.

3.1 Overall review

If you need to understand all the life cycle functions of vue2, you can copy this code and interrupt the running experience. (No need to run on scaffolding, just run directly)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../vue.js"></script>
</head>
<body>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
    <div id="root">
         <h2>当前的n值是: {
    
    {
    
     n }}</h2>
        <button @click="add">点我n+1</button>
        <button @click="bye">点我销毁</button>
    </div>

    <script>
        new Vue({
    
    
            el: '#root',
            data: {
    
    
                n: 1
            },
            methods: {
    
    
                add() {
    
    
                    this.n++    
                },
                bye() {
    
    
                    console.log('bye')
                    this.$destroy()
                }
            },
            beforeCreate() {
    
    
                console.log('beforeCreate')  
            },
            created() {
    
    
                console.log('created')
            },
            beforeMount() {
    
    
                console.log('beforeMount')
            },
            mounted() {
    
    
                console.log('mounted')
            },
            beforeupdate() {
    
    
                console.log('beforeupdate')
            },
            updated() {
    
    
                console.log('updated')
            },
            beforeDestroy() {
    
    
                console.log('beforeDestroy')
            },
            destroyed() {
    
    
                console.log('destroyed')
            }
        })
    </script>
</body>
</html>

3.2 Important lifecycle hooks

One is mounted: sending ajax, axios requests, starting timers, binding custom events, subscribing to messages, etc. [initialization operations].

One is beforeDestroy: Clear timers, unbind custom events, unsubscribe messages, etc. [finishing work].

Fourth, component programming

4.1 Overview

This section of componentized programming involves related configuration of components.

Here we need to understand the parent component and child component.

These two pictures can illustrate certain problems:
insert image description here

insert image description here
To summarize the standard definition of a component: a collection of local functional code and resources in an application.

4.2 Partial registration of components

Requirement: Import the Son component in the App component.

Let's talk about some imports first. A component references another component.

Please see the following code:

<template>
  <div class="box">
    子组件:<Son></Son>

  </div>
</template>

<script>
import Son from '@/components/Son.vue'
export default {
    
    
  name: 'App',
  components: {
    
    
    Son
  }
}
</script>

There are three points in total. First, introduce components.Here I would like to remind you that you can use @ as much as possible when quoting addresses, because if you use ./ or .../, it is easy to report a lot of errors later because of a file location change;

Then, register the component. When registering the component, if the component name is the same as the name of the component itself, it can be abbreviated;

The last thing is to use the component. When using the component, just write it in a label-like style.

4.3 Global Registration of Components

Global registration, as the name suggests, means that all components can use this globally registered component, so now let's take a look at how to globally register a component, let's take Son as an example.

Generally register some global things, all in the entry file, that ismain.jssuperior.

This requires the use of an api in Vue, Vue.component(), but the parameter of the api must be a key-value pair, with the component name on the left and the component on the right (otherwise an error will be reported). Components must be imported before they can be used.

code show as below:

import Vue from 'vue'
import App from './App.vue'

// 全局组件
import Son from '@/components/Son.vue'
Vue.component('Son', Son)

Vue.config.productionTip = false

new Vue({
    
    
  render: h => h(App),
}).$mount('#app')

You can use it directly after registration.

4.4 Slots

I wrote a very detailed article about slots before: The usage of vue slot slots and detailed explanation of scope slots

Here is a brief summary of the following points. The premise of the summary is that, following the case just now, the parent component is App and the child component is Son.

Then let's review the understanding of slots, which is actually to leave a space in the child component and fill it in the parent component. That's actually what we do.

4.4.1 Default slots

First, put a position in the child component:
insert image description here
Next, place the content in the parent component:
insert image description here
the final effect:
insert image description here
the slot just above, we call it the default slot.

4.4.2 Named slots

A named slot means a named slot.

Here is a requirement: two slots are required, one named one and the other named two. The contents of the two slots are different.

So we first place the slot in the child component,And give the slot a name.
insert image description here
Then write the slot content in the parent component, and correspond to the slot:
insert image description here
the final effect:
insert image description here

Five, information transfer between components

There are many kinds of communication between components. The contents reviewed in this section are: parent to child using props (the most basic), child to parent (custom event), ref to pass data, event car, and Vuex. It is a relatively comprehensive summary.

You can read these two articles for details. The following is just a review and will not be particularly detailed:
Data sharing between Vue components explains
the principle and standard writing of the vue event car to realize the value transfer of sibling components.
In vue, ref is used to achieve more flexible subdirections parent value

5.1 Passing values ​​from parent to child

The way to pass values ​​from parent to child is very simple: use props.

The parent component uses one-way binding to pass data to the child element, and the child element receives it using props. The following is the code part.

parent component:

<template>
  <div class="box">
    <Son :students="students"></Son>
  </div>
</template>

<script>
import Son from '@/components/Son.vue'
export default {
    
    
    name: 'App',
    data() {
    
    
        return {
    
    
            students: [
                {
    
    name: 'zxd', age: 20},
                {
    
    name: 'wxy', age: 20}
            ]
        }
    },
    components: {
    
    
        Son
    }
}
</script>

Subassembly:

<template>
  <div class="box">
    <ul>
        <li v-for="s in students" :key="s.id">
        {
    
    {
    
     s.name }}--{
    
    {
    
     s.age }}</li>
    </ul>
  </div>
</template>

<script>
export default {
    
    
    name: 'Son',
    props: ['students']
}
</script>

5.2 Passing value from child to parent

Custom events are used to pass values ​​from the child to the parent.

Events are defined in child components and triggered in parent components.

Here we need to understand the $emit method, which can be understood as triggering and triggering custom events. Of course, triggering a custom event is premised that the custom event is defined.

We write a custom event in the parent component:
Note here that this custom event is bound to the child component:Whoever binds the custom event will trigger it.
insert image description here

Then take a look at the code of the subcomponent: click the button, the add function is called, and the custom event fun defined in the parent component is triggered. Then in the child component, the custom event is called.

        <button @click="add">发送信息</button>
    </ul>
  </div>
</template>

<script>
export default {
    
    
    name: 'Son',
    props: ['students'],
    data() {
    
    
      return {
    
    
        baby: {
    
    
          age: 20,
          name: 'wxy'
        }
      }
    },
    methods: {
    
    
      add() {
    
    
        this.$emit('fun', this.baby);
      }
    }

After the custom event in the child component is triggered or called, the parent component will execute a callback function: in this callback function, the parameters passed by the child component can be received:

    methods: {
    
    
        get(value) {
    
    
            this.message = value;
            console.log(value)
        }
    }

Even if the steps are completed:
insert image description here
some readers may not understand why the steps are like this, here is an explanation: we use event binding in the parent component to bind a custom event fun to the child component. Because whoever binds the custom event will trigger it. So use $emit to trigger custom events in subcomponents. Two parameters are required for custom event triggering, one is the name of the custom event, and the other is the parameters required by the custom event. After the event is triggered, there will be a callback function. The callback function is in the parent component, so the parent component can receive the parameters passed by the child component.

If you haven't understood yet, let me talk about triggers and callbacks. This is about talking about native js. Take a look at the code below. In the code below, the click event is actually triggered, and then there is a callback after the trigger. In the above example too, trigger in the child component and call back in the parent component:

<button class="btn"></button>
<script>
	var btn = document.querySelector('btn')
	btn.addEventlistner('click', () => {
    
    
		alert('123')
})
</script>

If you don't understand it anymore, go to review the content of custom functions.

5.3 Event car

Regarding the event car, the blog linked above is actually very clear. But I will try to make it as clear as possible here.

Let's review the principle:
insert image description here
we call x an event vehicle, and x is regarded as a contact party, D can give data to x, and A can get data from x. This section needs to use the idea of ​​the previous section - custom events. We can trigger custom events through x, pass parameters to x, and execute callbacks through x to get parameters. This has very high requirements for x: x needs to be visible to all components (all components can access x), and x also needs to be able to use on and emit.

What kind of x meets the above conditions? on the prototype. Methods in the prototype are visible to all components. Write the standard writing here. If you want to analyze the principle, please move to the blog linked above.

First configure the following entry file main.js:

import Vue from 'vue'
import App from '@/App.vue'
Vue.use(App)

new Vue({
    
    
    render: h => h(App),
    beforeCreate() {
    
    
        Vue.prototypes.$bus = this
    }
}).$mount('#app')

Here, $bus is the x just now, which can be called a data bus or an event bus.

Then you can use it to pass data. Two components are set here, component A and component B. We pass data between these two sibling components. A passes to B.

Let's take a look at the code of A first. In A, use emit to trigger a custom event:

<template>
    <div class="box"></div>
</template>

<script>
export default {
    
    
    name: 'A',
    data() {
    
    
        return {
    
    
            me: {
    
    
                name: 'qklxmy',
                age: 20,
                job: 'zhongruan'
            }
        }
    },
    created() {
    
    
        this.$bus.$emit('toB', this.me)
    }
}
</script>

<style scoped></style>

Look at B again, on is used in B, the function of on is actually to receive the parameters in the custom event and call back:

<template>
</template>

<script>
export default {
    
    
    name: 'B',
    mounted() {
    
    
        this.$bus.$on('toB', (value) => {
    
    
            console.log(value)
        })
    }

}
</script>

<style scoped></style>

The above is the usage of the event car.

Six, routing

This section will review the configuration of routing, the basic usage of routing, and nested routing. The content of this section requires a certain understanding of routing: in single-page applications, routing plays the same role as links. Routing can be understood as a key-value correspondence, just like a link, which will lead to a new page after clicking. Routing also plays this role, but the rules are written in the routing rules.

6.1 Routing configuration

6.1.1 Entry file configuration

First configure the entry file main.js

import Vue from 'vue'
import App from '@/App.vue'
//引入路由器
import VueRouter from 'vue-router'
//引入路由规则
import router from '@/router/index'

Vue.use(VueRouter)

new Vue({
    
    
    render: h => h(App),
    router: router
}).$mount('#app');

Let's analyze the entry file:

Excluding the most basic configuration before, the router and routing rules are imported. And the router needs to be registered to introduce the following; the router file must also be configured in Vue.

6.1.2 Routing rule configuration

The routing rules are in the router folder:
insert image description here
Then we configure the routing rules:

import VueRouter from 'vue-router'

export default new VueRouter({
    
    
    
})

In this code, the router is first introduced, and then a VueRouter object is created, and the routing rules are placed inside, which we will talk about later. However, the written routing rules need to be accessible by the router, so export default is required.

6.2 Basic use of routing

Let's take a look at the effect first, and then analyze it step by step after the effect comes out.

After running, the first thing you see is:
insert image description here
After clicking Home: After
insert image description here
clicking About:
insert image description here
Please see the change of the link above: when we click Home, the link corresponds to /home, and the following shows Home; when we click About, the link corresponds to /about , Show About below.

The above is the link, link rules (routing, routing rules). So let's start with the routing rules first, introduce components on it, and write the routing rules below:

import VueRouter from 'vue-router'
//组件引入
import About from '@/Pages/About.vue'
import Home from '@/Pages/Home.vue'

export default new VueRouter({
    
    
    routes: [
        {
    
    
            path: '/about',
            component: About
        },
        {
    
    
            path: '/home',
            component: Home
        }
    ]
})

And write out the link and the place where the link is displayed in the app (the place where the route is displayed and the route is displayed), router-link and router-view. Among them, router-link needs to add a to, followed by the address.

<template>
  <div class="box">
    <router-link to="/home"><button>Home</button></router-link>
    <router-link to="/about"><button>About</button></router-link>

    <router-view></router-view>
  </div>
</template>

<script>
export default {
    
    
    name: 'App'
}
</script>

<style scoped>

</style>

6.3 Nested routes

Still look at the effect first.

Initial page:
insert image description here
Click About:
insert image description here
Click any button in about:
insert image description here
You can see that the route is nested in about.

Looking at the routing rules, there is a children inside. And you need to remember that in the routing rules, the rules of the sub-components do not need to be written completely.

import VueRouter from 'vue-router'
//组件引入
import About from '@/Pages/About.vue'
import Home from '@/Pages/Home.vue'
//嵌套组件
import Messages from '@/Pages/Messages'
import News from '@/Pages/News'

export default new VueRouter({
    
    
    routes: [
        {
    
    
            path: '/about',
            component: About, 
            children: [
                {
    
    
                    path: 'messages',
                    component: Messages
                }, 
                {
    
    
                    path: 'news',
                    component: News
                }
            ]
        },
        {
    
    
            path: '/home',
            component: Home
        }
    ]
})

Look at the about component again: In the address of router-link, the address needs to be written completely.

<template>
  <div class="box">
    <router-link to="/about/news"><button>News</button></router-link>
    <router-link to="/about/messages"><button>Messages</button></router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
    
    
    name: 'About'
}
</script>

<style scoped>

</style>

postscript

This article explains some basic knowledge of Vue2, not so much the basics, but the basics - things that must be mastered.

There are still many things that need to be used in the project. If you want to know more, you can follow me and follow some of my blogs.

That's all, it's not easy to explode the liver, and I spend my blogging time every day. Hope to get a wave of likes and attention. Although it won't bring me a lot of income, but every time I click on it, I will be very happy to see the little red dots in the place of likes and favorites.

Thank you all, and best of luck to you all!

Guess you like

Origin blog.csdn.net/zxdznyy/article/details/130132096