[Getting started with vue in half an hour] The easiest way to get started with vue

Foreword (!important)

If you want to get started with vue, then this blog is very suitable for you. Although you can go to the rookie tutorial , you can go to the MDN official website , you can go to w3cschool to find knowledge about vue. But when you don't quite understand the official description, returning to this blog may be very friendly to you.

You can get started with vue in half an hour, but it took me many hours to write this blog.
The blogger is a person who likes traditional Chinese culture, especially Chinese medicine. I have read "Treatise on Febrile Diseases" written by the medical sage Zhang Zhongjing. . I am afraid that future generations will not understand the meaning of this prescription, and I am afraid that the function of this medicine has not been explained clearly.
I seem to have the same feeling when I write this blog. .
If you are a programmer with a Vue foundation, you can check the relevant basic knowledge in this blog.
If you are a programmer who is new to vue, then I just want to say to you: isn't it just a little vue? do it! ! !
As long as you have a certain language organization and summarization ability, you can speak official language during the interview. But when you are learning something, what are you doing so officially? How easy to understand how to come.

Many bloggers on the Internet have written introductory tutorials in this area, and there are also such teaching videos. But I want to convey to you a more down-to-earth vue in a more transparent way, so that the understanding ability is slightly poorer, the ability to accept new things is poorer, so that you can learn vue by yourself, and you who are confused by beginners can find a suitable vue here. your way of understanding.

ok, start text


Prerequisites for learning vue

If you have studied the three front-end swordsmen (HTML, CSS, JavaScript) , it is best to have also learned JQuery . You must have a certain front-end foundation before you can learn vue. Because vue is a thing based on the front-end three musketeers .

If you have this basic knowledge, then please read on!

If you don't have this basic knowledge, you still want to learn vue. My suggestion is to connect this blog three times, then quit this blog, and come back after you have finished learning and mastered the front-end three musketeers. Just don't want you to waste time. If you want to run, you must first master walking .


What is vue?

Vue is a front-end JavaScript framework for building web user interfaces. It is a progressive framework.

It is necessary to clarify three concepts here:
1. What is a frame?

A frame can be understood as a frame for photos, or as a country.

There are requirements for photos to be put into photo frames. For example, this photo frame requires a photo size of 500px*400px. Then if the size of your photo does not match the size required by this photo frame, it will not fit in.

A country has its own territory, and when you are in this country, you will enjoy the rights of this country. Of course, this country has its own laws and rules. If you cannot abide by the laws and rules of this country, you will not be able to stay in this country.

So the framework is a kind of specification. The framework can provide you with convenience, but at the same time, the framework has its own set of rules and corresponding restrictive products.

2. What is progressive?

Progressive can be understood as a way that is easy to learn, easy to use, very flexible, efficient, and progressive

For example, if you want to become a Rubik's cube master, you must first master the second-order Rubik's cube, then gradually master the third-order Rubik's cube, then the fourth-order Rubik's cube, and then the higher-order Rubik's cube. This is done step by step. In programming, it means that you take whatever you want to use.

For example, if there is a long code, you only need to use two lines of code, and you can just use it. This is the concept of gradualism.
If there is a long piece of code, and you want to use two lines of code, you have to take all the codes to use these two lines, then this is non-progressive. For example, plug-ins, you may only use a little bit of the plug-in, but you have to download and reference the entire plug-in, this is the concept of non-progressive

So progressive means that there are not too many rules, not too many constraints, and not too many restrictions. If I want to use a code, I just take this one.

3. What is a Progressive Framework?

A progressive framework is a product that provides convenience for you without too many rules, without too many constraints, and without too many restrictions.

Progressive framework uses modern web technologies such as Web Components, Service Workers, and Web App Manifests, etc. to provide faster loading speed, offline access, and native app-like user experience. Progressive frameworks also allow developers to gradually add advanced features to ensure compatibility with older browsers and devices. Common progressive frameworks include Vue.js、React、Angularetc.

The advantages of the progressive framework are reflected in the following points:

Flexibility: Due to the step-by-step application feature, developers can freely choose to use or not use various functions and modules of the framework.

Reusability: Components and modules in the Progressive Framework are self-contained and can be easily transferred to be used in other projects.

Extensibility: Developers can add new functions and modules as needed without modifying existing code.

Performance: Progressive frameworks typically run more efficiently because they contain only the necessary code needed by the application.

After understanding these three basic concepts, it is easy to understand what is vue.
Vue is a framework developed by others. Using this framework, we can develop web pages quickly and efficiently.

Vue is similar to jquery, it is something packaged by others, you can use it directly. In jQuery, we use a very simple way to get elements.

let but = document.querySelectorAll('#button');
//等价于
$('#button')
//这个$就是人家封装好的东西,直接拿来用

In Vue, there are also things packaged by others, but the rules of use are different.


How to import vue

There are two commonly used import methods

The first:

Local import: download the Vue.min.js file from the vue official website , and <script src=""></script>import it with tags.
Address: Click to download

The second type:

Introduced online:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.js"></script>


instantiate an object and create an object

⭐ Instantiation can be simply understood as creation, but there is a difference between instantiation and creation in essence.

What is the difference between instantiating an object and creating an object?

  • Creating an object means allocating space in memory for a new object. In JavaScript, objects can be created using object literals, constructors, and more. Creating an object just allocates space for an object in memory, and does not initialize or assign a value to this object.
  • The instantiated object is to assign the created object to a variable, and initialize or assign the object as needed. Instantiating an object is to be able to use the object, not just occupy a space in memory. In JavaScript, use the new operator to instantiate an object, usually using a constructor to create an object instance.

Instantiate a vue object

Vue.createApp()is a global API in Vue.js 3.x, used to create a new Vue application instance. This function receives an object containing component options as a parameter, and returns an application instance object, which can be used to mount on DOM elements for rendering and interaction.

You createApp()can define your own components, directives, filters, etc. in the application, and you can easily perform operations such as state management, routing control, and server interaction.

⭐The following is the template, which can be used 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>
</head>
<body>
    <div id="app">
 				
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.js"></script>
    <script>
        Vue.createApp({
      
      
            data() {
      
      
                return {
      
      
                    // 写变量
                }
            },
            methods:{
      
      
                    // 写函数,写方法
            }
        }).mount('#app')
    </script>
</body>
</html>

⭐ Simple to use:

<!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>
</head>
<body>
    <div id="app">
        <div v-show="flag"> {
   
   {name}} </div>
        <button @click="show">显示</button>
        <button @click="clo">隐藏</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.js"></script>
    <script>
        Vue.createApp({
      
      
            data() {
      
      
                return {
      
      
                    name:'爱学习的akali king',
                    flag:true
                }
            },
            methods:{
      
      
                    show(){
      
      
                        this.flag = true;
                    },
                    clo(){
      
      
                        this.flag = false;
                    }
            }
        }).mount('#app')
    </script>
</body>
</html>

⭐Effect:
insert image description hereThis is a switching effect implemented with vue. The writing looks strange, and this is its syntax. Next, let's walk into the syntax of vue to see what it is in detail.


template syntax

insert image description hereThe definition on the official website is very clear and not difficult to understand.
⭐Mainly look at the template syntax of vue:

1. Interpolation expression

Grammar format: { {value in data}}
insert image description here
⭐⭐⭐Key point:
in the div in the above figure{ {name}}is called an interpolation expression. What is interpolated is the value, whose value? The value of name!
How to understand the name here?

				return{
    
    
					name:‘爱学习的akali king’ 
				}

This sentence here is equivalent to var name = ‘爱学习的akali king’
just omitting the way of declaring the variable, nameand it is still a variable. So the interpolation expression nameis a variable. When return{}the namevalue in the interpolation expression is changed, the things displayed in the interpolation expression on the page will also change.

Also known as. return{}Everything in is a variable, you can write arrays, objects, etc.
You can write like this:

                return {
    
    
                    name:'爱学习的akali king',
                    flag:true,
                    arr:[
                        {
    
    msg:'你'},
                        {
    
    msg:'好'},
                        {
    
    msg:'帅'},
                        {
    
    msg:'啊'},
                    ],
                    price:10,
                    str:''
               }

Let's feel this variable again:

insert image description here


2. v-text and v-html directives

⭐These two instructions are easy to understand and intuitive. Take the following code as an example.

<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>
</head>
<body>
    <div id="app">
        <div v-text="example1"></div>
        <div v-html="example1"></div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.js"></script>
    <script>
        Vue.createApp({
      
      
            data() {
      
      
                return {
      
      
                    example1:"<h1>v-text显示效果</h1>",
                    example2:"<h1>v-html显示效果</h1>"
                }
            },
            methods:{
      
      

            }
        }).mount('#app')
    </script>
</body>
</html>

⭐Effect:
insert image description here⭐According to the above code and effect, we found the difference between v-textand v-html:
v-textdo not parse tags, which is equivalent to parsable tags in native js innerText
v-html, which is equivalent to native jsinnerHTML


3. v-bind command

v-bindInstructions represent dynamic binding properties, and the abbreviation is (:)

<div v-bind:title="111">绑定属性</div>

The above notation is equivalent to the following

<div :title="111">绑定属性</div>

insert image description here


4. v-on command

v-onInstructions represent event bindings, which can be abbreviated as@事件名称=‘函数名称’

<button v-on:click="fun">新增</button>

The above notation is equivalent to the following

 <button @click="fun">新增</button>

If you need to pass parameters, you can write like this

 <button @click="fun(参数1,参数2)">新增</button>

⭐After the event is bound, you need to write the corresponding function for the event. In the Vue object, add the attribute methods, methods are JSON objects, containing key-value pairs one by one, the value is function

<!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>
</head>
<body>
    <div id="app">
        <button v-on:click="fun">新增</button>
        <button @click="fun2">新增2</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.js"></script>
    <script>
        Vue.createApp({
      
      
            data() {
      
      
                return {
      
      
 
                }
            },
            methods:{
      
      
                fun(){
      
      
                    console.log(1);
                },
                fun2(){
      
      
                    console.log(2);
                }
            }
        }).mount('#app')
    </script>
</body>
</html>

⭐Effect:
insert image description here

5. v-model command

v-modelIt is one of the commonly used instructions in Vue, mainly used to realize two-way binding. It can bidirectionally bind form elements (such as input, textarea, etc.) and data in the Vue instance, that is, when the value of the form element changes, the corresponding data in the Vue instance will be updated synchronously; When a change occurs, the value of the form element is updated accordingly.

The usage of the ⭐ v-modeldirective is very simple, just use it on the form element v-modeland point its value to a data attribute in the Vue instance.

<!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>
</head>
<body>
    <div id="app">
        <input v-model="message" type="text">
        <p>你好: {
   
   { message }}</p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.js"></script>
    <script>
        Vue.createApp({
      
      
            data() {
      
      
                return {
      
      
                    message: '小朋友'
                }
            },
            methods:{
      
      

            }
        }).mount('#app')
    </script>
</body>
</html>

⭐Effect:
insert image description here

In the example above, we v-model="message"bound to an input element and then displayed the value of the message attribute on the page. When the user enters content in the input box, the value of the message attribute will be updated at the same time; conversely, if we modify the value of the message attribute in the Vue instance, the content in the input box will also change accordingly.

It should be noted that v-modelit can only be used on form elements and their components, and it is only valid on form elements. v-modelIt has no effect on non-form elements .


6. v-if and v-show instructions

v-ifand v-showare instructions used to control the display/hide of elements in Vue.js.

⭐v-show:

<!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>
</head>
<body>
    <div id="app">
        <button v-show="flag">苹果</button>
        <br>
        <br>
        <button @click="show">显示</button> 
        <button @click="clo">隐藏</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.js"></script>
    <script>
        Vue.createApp({
      
      
            data() {
      
      
                return {
      
      
                    flag:true
                }
            },
            methods:{
      
      
                show(){
      
      
                    this.flag=true;
                },
                clo(){
      
      
                    this.flag=false;
                }
            }
        }).mount('#app')
    </script>
</body>
</html>

⭐Effect:
insert image description here


⭐v-if

<!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>
</head>
<body>
    <div id="app">
        <button v-if="flag">苹果</button>
        <br>
        <br>
        <button @click="show">显示</button> 
        <button @click="clo">隐藏</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.global.js"></script>
    <script>
        Vue.createApp({
      
      
            data() {
      
      
                return {
      
      
                    flag:true
                }
            },
            methods:{
      
      
                show(){
      
      
                    this.flag=true;
                },
                clo(){
      
      
                    this.flag=false;
                }
            }
        }).mount('#app')
    </script>
</body>
</html>

⭐Effect:

insert image description here


⭐From the above understanding, it can be seen v-ifthat v-showthe differences are as follows:

v-ifIt is to dynamically add or remove elements according to the true and false values ​​of the expression. When the expression falseis true , the element will not be rendered into the DOM, and when the expression becomes true true, the element will be rendered into the DOM.
v-showIt controls the display/hide of the element by setting the display property on the element. When the expression falseis , the element will be hidden but still exist in the DOM; when the expression trueis, the element will be displayed.
Therefore, if you need to frequently switch the display/hidden state of an element, use v-showcan get better performance; if the display/hide state of an element rarely changes, and the element is more complex, use v-ifcan reduce unnecessary DOM operations.


7. v-for instruction

v-foris an instruction in Vue.js for rendering list data. It can iterate over an array or object and render each element as a corresponding HTML element.

v-forThe main use of is to dynamically generate list data in Vue.js applications. Usually, directives are used when we need to display some views based on a collection of data v-for.

v-forDirectives can be used in Vue.js templates as follows:

<div v-for="(item, index) in items" :key="id">
  {
   
   { item }}
</div>

Among them, itemsis an array, in the above example, v-foran element will be created for each element in the array <div>, and the current element will be stored in itema variable ( for an array, itemit is each item in the array ) and the element The index of is stored in indexa variable. :keyAttributes are used to improve rendering performance ( :keybinding uniquely identified values, such as id, ID number, etc. ), to ensure that Vue.js can correctly track the state of each element.

The v-for directive can also be used to iterate over the properties of an object:

<div v-for="(value, key) in object" :key="key">
  {
   
   { key }}: {
   
   { value }}
</div>

v-forAn element will be created for each property in the object <div>, storing the value of the property in valuea variable and the name of the property in keya variable.

This is the beginning of vue. Once you get started, you have mastered the writing method and basic concepts of vue2, and then learn vue3, which is easier to learn.

Guess you like

Origin blog.csdn.net/dyk11111/article/details/130613368