This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

The official document is very detailed about how to use Vue. Here, I will sort out the knowledge learning process of Vue again based on my personal understanding.

Why use Vue

As front-end technology continues to evolve, front-end development can handle more and more business, and web pages become more powerful and dynamic, all of these advances are made possible by JavaScript. In current development, a lot of server-side code has been put into the browser to execute, resulting in thousands of lines of JavaScript code that are linked to various HTML and CSS files, but lack formal organization. This is why more and more front-end developers are using JavaScript frameworks. Currently popular front-end frameworks include Angular, React, Vue, etc.

Vue is a set of progressive frameworks for building user interfaces. Progressive means that Vue is designed to be applied layer by layer from the bottom up. Vue’s core library focuses only on the view layer, making it easy to get started and integrate with third-party libraries or existing projects. On the other hand, when combined with modern toolchains and various supporting libraries, Vue is perfectly capable of providing drivers for complex, single-page applications.

Create a Vue app

The easiest way to introduce a Vue is to import a CDN package:

<script src="https://unpkg.com/vue@next"></script>
Copy the code

First create a label:

<div id='root'></div>
Copy the code

CreateApp creates an application and stores it in the app variable. The parameter passed in indicates how the outermost component of the application should be displayed.

Vue programming is data-oriented programming, which references the MVVM design pattern. M stands for model, where data is the data layer; V for view, template for view layer; The VM represents the viewModel, and the connection between the data and the view is the view data connection layer, which is done by the Vue components, not the Vue application.

const app = Vue.createApp({
    data(){
        return{
            message:'hello world'}},template:/*html*/` 
      
{{message}}
`
}) Copy the code

Vm represents the root component instance of a Vue application.

const vm = app.mount('#root')
Copy the code

In the console, we can get the data on the root node via vm.$data.message or vm.

Vue lifecycle functions

A lifecycle function is a function that automatically executes at some point in time.

The function beforeCreate() is executed automatically before the instance is generated to analyze the dependency injection and bidirectional binding created() is executed automatically after the instance is generated to determine if the template option exists in the instance - it exists to compile the template into Render function - There is no such thing as compiling innerHTML in 'root' to template beforeMount() automatically replaces the Dom in 'root' with the new Dom after the template has been compiled as a function but before it is mounted to the page Mounted () Component content is automatically executed after rendering to the page if changing data. BeforeUpdate () Automatically executed immediately when data in data is sent changes Virtual DOM rerenders the page updated() When data data is changed Unmount() automatically executes 'app.unmount()' after page is updated to cancel mounting, View no longer takes over the node mounted by 'root'. BeforeUnmount () Automatically executes ummounted() when Vue application fails, instance destruction when Vue application fails. It is automatically executed when the Dom is completely destroyedCopy the code

Template syntax

{{message}} in template uses template syntax, and JavaScript expressions can be used between curly braces.

The Vue directive of V-HTML can display its property values in HTML on div tags.

The V-bind directive binds a property to data, short for:.

The V-once directive causes variables to be used only once, reducing useless rendering and improving performance.

<div v>{{'a' + 'b'}}</div>
<div v-html:title="message"></div> <! -- Display message contents -->
<div v-bind:id="id">{{message}}</div>
<div v-once>{{message}}</div>
Copy the code

V-if, V-ELSE, and V-else -if determine whether to display the label based on the value of the expression.

V-on can bind events, abbreviated as @.

<div v-on:click="handleClick"></div>
Copy the code

Dynamic parameters can be used in directive parameters by using JavaScript expressions in square brackets.

data() {
    return {
	message: 'hello world'.name: 'title'The event:'mouseenter'}}Copy the code
<div@ [event] ='handleEvent' :[name] ='message'></div>
Copy the code

Use the. Prevent modifier directly after the bound event to prevent the default behavior.

Data, methods, compute properties, and listeners

const app = Vue.createApp({
    data(){
        return{
            message: 'hello world'.count: 1.price: 5}},method: {formatString(string) {
            returnstring.toUpperCase(); }},watch: {price(current, prev) {
            setTimeout(() = >{
		console.log(prev, current)
            },3000)}},computed: {total() {
            return this.count * this.price; }},template:` 
      
{{formatString (message)}}
{{total}}
`
}) Copy the code

In the console, we can get the data on the root node via vm.$data.message or vm.

Method’s this in app points to an instance of Vue, so don’t use arrow functions when defining methods.

Computed data has strong semantics, and when data changes, the data in computed attributes is recalculated.

The computed data is recalculated only when the content dependent on the computed property changes. Methods in Method are re-executed whenever the page is re-rendered.

Watch can monitor the change of variables and execute corresponding functions. Each function has two parameters, representing the current value and the value before the change respectively.

For both computed and Method, use computed, because data is cached when it doesn’t change; Both computed and Watch can achieve functions using computed because they are much simpler.

Style binding

You can specify class and style as strings, arrays, and objects.

.red {
    color: red;
}
.green {
    color: green;
}
Copy the code
const app = Vue.createApp({
    data(){
        return{
            message:'hello world'.classString: 'red'.classObject: {red: false.green: true},
            classArray: ['red'.'green', {class3: true.class4: false}].styleString: 'color: yellow'.styleObject: {
                color: 'orange';
                background: 'yellow'; }}},template:` 
      
{{message}}
{{message}}
{{message}}< demo class='green'/>
// inline style
{{message}}
{{message}}
`
}) app.component('demo', {template:`
one
two
`
}) Copy the code

The style of the parent component is passed to the child component, and the binding style can only be applied when there is only one outermost node in the component when the component is called.

Conditions apply colours to a drawing

The V-if, V-else, and V-else -if directives are used to conditionally render a block of elements, rendering the block if the directive returns truthy and not falsy. These instructions control the display and hiding of the element by directly controlling its presence or absence in the DOM.

The V-show directive also renders a block of elements by the return value of the directive. It controls whether elements are displayed or not with the style display: None.

We use V-show if we want to switch between elements frequently, because it does not create and destroy DOM elements frequently, which is better. Otherwise we use V-if because it has a low initial rendering overhead.

We use v-if on

V-if has a higher precedence than V-for. Do not use both directives on the same element.

The list of rendering

The V-for directive is used to loop out data from an array or object. The first parameter is mandatory and the other parameters are optional.

There are two arguments to traversing a number group, the first value and the second index.

The object is traversed by three parameters, the first value, the second key, and the third index.

data() {
    return {
	listArray: ['hello'.'world'.'foo'.'bar'].listObject: {
            firstName: 'Steven'.lastName: 'Jobs'}}},method: {
    handleClick() {
	this.listArray.pop(); }}Copy the code
<div v-for='(item, index) in listArray'>
	{{index}} - {{item}}
</div>
<button @click='handleClick'>
<div v-for='(value, key, index) in listObject'>
	{{index}} - {{key}} - {{item}}
</div>
Copy the code

Because of v-for’s “update in place” policy, we need to declare a unique key value for each loop element. This value can only be a number or string, and the value of the key binding should not be index.

<div v-for='(item, index) in listArray' :key='item'></div>
Copy the code

There are two ways to change the contents of an array. One is to use the array change function:

Push (), pop(), Shift (), unshift(), splice(), sort(), and reverse()

Another option is to replace the array directly:

Filter (), concat(), and slice()

The array of the V-for loop can be either a evaluated property or a method with an array return value:

computed: {
    evenNumbers(){
	return this.numbers.filter(number= > number % 2= = =0)}}Copy the code
<div v-for='item in evenNumbers' :key='item'></div>
Copy the code

V-for also accepts an integer:

<div v-for='item in 10' :key='item'></div>
Copy the code

V-if has a higher priority than v-for. If you want to use both, you can do this:

<template v-for='item in items' :key='item'>
    <div v-if='item % 2 ===0'>
	{{item}}
    </div>
</template>
Copy the code

The event processing

The V-ON directive lets us bind an event, abbreviated @ :

<button @click='handleClick'>click here</button>
Copy the code

Then we need to define this event in the Methods option:

methods: {
    handleClick() {
	alert('clicked! '); }}Copy the code

The default parameter is event. If you want to pass event with more than one parameter, you can use $event:

<button @click='addNumber(2, $event)'>click here</button>
Copy the code

Multiple events can be bound at the same time, but should be written as function calls, not function references:

<button @click='handleClick(), handleClick1()'>click here</button>
Copy the code

Event modifier

Event modifiers make it easy to deal with common requirements when an event is called, such as preventing further propagation of the event and preventing the default behavior of the event. This has the advantage of allowing us to focus only on the data logic in our methods, rather than on manipulation of the DOM.

Key modifier

When listening for keyboard events, we check for key details. Key modifiers allow us to restrict key calls to events.

Bidirectional binding in forms

Basic usage

The V-model is used for bidirectional binding on ,

In input and textarea, the V-Model uses the value property and input methods:

data(){
    return {
        message: 'hello'}},template:`   `
Copy the code

In checkBox and Radio, the V-Model uses the checked property and change methods. The bound value can be a Boolean, an array, or a string:

// The bound value is an array
data(){
    return {
        message: []}},template:` apple  banana  pear  {{message}} `
// Message === ['apple', 'banana']
Copy the code

In select, the V-model uses the value property and change methods:

Radio:

data(){
    return {
        message: ' '}},template:' {{message}} `
Copy the code

Multiple selection :(Ctrl + left mouse button multiple selection)

data(){
    return {
        message: [].// The properties of option are stored in an array and rendered with v-for
        options: [{text: 'apple'.value: 'apple'},
            {text: 'banana'.value: 'banana'},
            {text: 'pear'.value: 'pear'}}},template:` <select v-model='message' multiple> <! --> <option v-for='(option, index) in options' :value='option.value' :text='option.text' :key='index' /> </select> {{message}} `
Copy the code

Value binding

For checkBox, Radio, and SELECT, the value of the V-model binding is typically a static string.

If we want to bind a value to a dynamic property, we can do this using V-bind. V-bind can also bind input values to non-strings.

<select v-model='selected'>
    <option :value='{ number: 123}'>123</option>
</select>
<! Typeof vm.selected => 'object' vm.selected. Number => 123 -->
Copy the code

The value of the true-value and false-value attributes in the checkbox can be returned to the binding value according to checked.

<input 
    type='checkbox' 
    v-model='toggle' 
    true-value='yes' 
    false-value='no' 
/>
<! -- checked = true, then toggle = yes -->
Copy the code

The modifier

The V-Model synchronizes the value of the input box to the data after each input event is triggered. This can be converted to synchronization after the change event is triggered by using the.lazy modifier:

<input v-model.lazy='message' />
Copy the code

The.number modifier converts an input value to a numeric type; If the input type is number, Vue automatically converts:

<input v-model.number="age" type="text" />
<input v-model="amount" type="number" />
Copy the code

To filter leading and trailing whitespace, use the.trim modifier.