Vue.js basics (minimalist, self-use)

Vue.js

A progressive JavaScript framework for building user interfaces

JavaScript framework

Simplify Dom manipulation

Responsive Data Driven

Official Website: Vue.js (vuejs.org)

awesome vue

Charts: charts

Features:

■ 1. Adopt componentization (HTML+CSS+JS) mode to improve code reuse rate and make code easier to maintain

■ 2. Declarative coding, so that coders do not need to directly operate DOM, improving development efficiency

■ 3. Use virtual DOM + excellent Diff algorithm to reuse DOM nodes as much as possible

Imperative coding (step by step) = opposite => declarative coding

BeginnerVue

The full name of the axios framework ( ajax -I/O-system):

This is not a new technology. It is essentially an encapsulation of native XMLHttpRequest, which can be used in browsers and nodejs HTTP clients, but it is Promise-based and conforms to the latest ES specification. Has the following characteristics:

Create XMLHttpRequest request in browser Send http request in node.js Support Promise API interception request and response conversion request and response data cancel request automatically convert JSON data client support prevent CSRF/XSRF (cross-domain request forgery)

Delete the entire line: ctrl+shift+k

Common tags:

the: (item)

■ el is used to specify which container the current Vue instance serves, and the value is usually a css selector string

 id="root"
 ​
 el:'#root'

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>初识Vue</title>
     <!--引入vue-->
     <script type="text/javascript" src="../js/vue.js"></script>
 </head>
 <body>
     <!--
         1、想让Vue工作,就必须创建一个Vue实例,且要传入一个配置对象
         2、root容器里的代码依然符合html规范,只不过混入了一些特殊的Vue语法
         3、root容器中里的代码被称为【Vue模板】
         4、Vue实例和容器是一一对应的
         5、真实开发中只有一个Vue实例,并且会配合着组件一起使用
         6、{
   
   {xxx}}中的xxx要写js表达式,且xxx可以自动读取到data中的所有属性
         7、一旦data中的数据发生了改变,那么页面中用到该数据的地方也会自动更新
 ​
         注意区分js代码(语句)和js表达式
             1、表达式:一个表达式会产生一个值,可以放在任何一个需要值的地方
                 (1).a
                 (2).a+b
                 (3).demo(1)
                 (4).x == y ? 'a' : 'b'
 ​
            2、js代码(语句)
                 (1).if(){}
                 (2).for(){}
 ​
     -->
     <!--准备好一个容器-->
     <div class="root">
         <h1>{
   
   {name}},{
   
   {address.toUpperCase()}}</h1>
     </div>
 ​
     <script type="text/javascript">
         Vue.config.productionTip = false  //阻止 vue 在启动时生成生产提示。
 ​
         //创建Vue实例
         new Vue({
             el:'.root' , //el用于指定当前Vue实例为那个容器服务,值通常为css选择器字符串
             data:{  //data用于存储数据,供el所指定的容器去使用,值暂时写为一个对象
                 name:'宋一鲤',
                 address:'甘肃'
             }
         })
 ​
     </script>
 </body>
 </html>

The html contains some JS syntax codes, which are divided into two types:

  1. Interpolation syntax (double brace expressions)

    1. Function: Used to parse the content of the tag body

    2. Syntax: { {xxx}} , xxxx will be parsed as a js expression

###

 
<!--准备好一个容器-->
     <div id="root">
         <h1>插值语法</h1>
         <h3>你好,{
   
   {name}}</h3>
     </div>
 </body>
 ​
     <script type="text/javascript">
         Vue.config.productionTip = false //阻止 vue 在启动时生产提示
 ​
         new Vue({
             el:'#root',
             data:{
                 name:'jack'
             }
         })
     </script>

  1. Instruction syntax (starts with v-)

    1. Function: Parsing tag attributes, parsing tag body content, binding events

    2. Example: v-bind:href = 'xxxx', xxxx will be parsed as a js expression

<a v-bind:href="school.url">点我去{
   
   {school.name}}学习1</a>
         <a :href="school.url">点我去{
   
   {school.name}}学习2</a>
     </div>
 </body>
 ​
     <script type="text/javascript">
         Vue.config.productionTip = false //阻止 vue 在启动时生产提示
 ​
         new Vue({
             el:'#root',
             data:{
                 name:'jack',
                 school:{
                     name: '尚硅谷',
                     url: 'http://atguigu.com'
                 }
             }
         })
     </script>

One-way data binding:

Syntax: v-bind:href = "xxx" or abbreviated as: href

Two-way data binding:

Syntax: v-mode:value="xxx" or short for v-model="xxx"

 <!--普通写法-->
 单向数据绑定:<input type="text" v-bind:value="name"><br/>
 双向数据绑定:<input type="text" v-model:value="name"><br/>
 ​
 <!--简写-->
 单向数据绑定:<input type="text" :value="name"><br/>
 双向数据绑定:<input type="text" v-model="name">

Idea adds code snippets in setting

 

Two ways of writing el and data:

 //el的两种写法
        /* const  v = new Vue({
             // el: '#root',     //第一种写法
             data: {
                 name: '宋一鲤'
             }
         })
         console.log(v)
         setTimeout(() =>{
             v.$mount('#root')   //第二种写法
         },1000);*/
 ​
         //data的两种写法
         new Vue({
             el: '#root',
             //data的第一种写法:对象式
             /*data: {
                 name: '宋一鲤'
             }*/
 ​
             //data的第二种写法:函数式
             data:function (){
                 return{
                     name:'宋一鲤'
                 }
             }
         })
 
 

The Object.defineProperties method prints an error on the console:

Uncaught TypeError: Property description must be an object: a at Function.defineProperties (<anonymous>)

Correct solution:

let person = {
 ​
 •      name:'张三',
 ​
 •      sex:'男',
 ​
 •      // age:18 
 ​
 •    }
 ​
 ​
 ​
 •    Object.defineProperties(person,{'age':{
 ​
 •      value : 18,
 ​
 •    }
 ​
 •    })
 ​
 •    console.log(person)

Schematic diagram of data proxy (06_data proxy - 3. Data proxy in Vue):

 

console.log(event.target): print the elements in the target file

 v-on:xxx=@xxx

Set scroll event:

overflow: auto;

@scroll="demo": Set the scroll event of the scroll bar

@wheel="demo": set the mouse wheel scroll event

vm is a Vue instance object:

const vm = new Vue({
        el:'#root',
        data:{
        name:'尚硅谷',
        },
        methods:{
          showInfo(event){
            // console.log(event.target.innerText);
            console.log(this==vm);
            //alert('同学你好')
             } 
        }
    })

Basic use of events in Vue:

1. Use v-on:xxx or @xxx to bind events. Where xxx is the event name;

2. The event callback needs to be configured in the methods object, which will eventually be on xm;

3. Do not use arrow functions for functions configured in methos! Otherwise this is not a vm;

4. The functions configured in methods are all functions managed by Vue, and this points to the vm or component instance object;

5. @click="demo" and @click="demo($event)" have the same effect, but the latter can pass parameters;

Keyboard events: @keydown and @keyup.

1. Commonly used button aliases in Vue:

carriage return => enter

delete => deelete (captures "delete" and "backspace" keys)

exit => esc

space => space

Newline => tab (special, must be used with keydown)

up => up

down => down

left => left

right => right

2. Vue does not provide an alias button, you can use the original key value to bind, but pay attention to converting to kebab-case (short horizontal line naming)

3. System modifier keys (special usage): ctrl, alt, shift, meta

(1). Use with keyup: while pressing the modifier key, press other keys, and then release the other keys, the event is triggered

(2). Use with keydown: normal trigger event

4. You can also use keyCode to specify specific keys (not recommended)

5. Vue.config.keyCode. Custom key name = key code, you can customize the case alias

Visual Studio Code selects multiple lines of input at the same time, Alt + Shift + left mouse button to select multiple lines

IntelliJ IDEA selects multiple lines of input at the same time, Alt + left key selects multiple lines

split(): split [string. Slice a string by specifying a delimiter and return a list of split strings (list)

Computed property:

1. Definition: The attribute to be used does not exist, it must be calculated from the existing attribute

2. Principle: The bottom layer uses the getter and setter provided by the Object.defineproperty method

3. When is the get function executed?

(1). It will be executed once when it is read for the first time

(2). When the dependent data changes, it will be called again

4. Advantages: Compared with the implementation of methods, the internal cache mechanism (multiplexing) is more efficient and easy to debug.

5. Remarks:

1. Computed attributes will eventually appear on the vm, which can be read and used directly.

2. If the calculated attribute is to be modified, the set function must be written to respond to the modification, and the set will cause the data on which the calculation depends to change

shift+tab: reduce indentation

Remember the characteristics of the arrow function: there is no this itself, but you can call this in the upper and lower domains for your own use

Interview question: What is the role of the key in react and vue? (key internal principle)

1. The role of key in virtual DOM:

The key is the identifier of the virtual DOM object. When the data changes, Vue will generate a [new virtual DOM] according to the [new data].

Then Vue can compare the difference between [new virtual DOM] and [old virtual DOM]. The comparison rules are as follows:

2. Comparison rules:

(1). The same key as the new virtual DOM is found in the old virtual DOM:

<1>. If the content in the virtual DOM has not changed, use the previous real DOM directly!

<2>. If the content in the virtual DOM changes, a new real DOM is generated, and then the previous real DOM in the page is replaced

(2). The same key as the new virtual DOM was not found in the old virtual DOM

Create a new real DOM, then render to the interface

3. Possible problems caused by using index as key

1. If the data is destroyed in sequence operations such as adding in reverse order and adding in reverse order:

Will update the real DOM that is not necessary ==>> The interface effect is fine, but the efficiency is low

2. If the structure also contains the input class DOM:

Will generate wrong DOM update ==>> interface has problems

4. How to choose a key during development? :

1. It is best to choose the unique identifier of each piece of data as the key, such as unique values ​​such as id, mobile phone number, ID number, student number, etc.

2. If there are no reverse sequence operations such as reverse addition and reverse deletion of data, it is only used to render the list for display

There is no problem using index as key

Code folding:

// #region
.......
// endregion

DevTools

Collect form data:

If: <input type="text"/>, then v-model collects the value of value, and the user enters the value.

If: <input type="radio"/>, then the v-model collects the value of value, and the value must be configured for the label.

若:<input type="checkbox"/>

1. If the value attribute of the input is not configured, then the collection is checked (checked or unchecked, it is a Boolean value)

2. Configure the value attribute of input

(1). The initial value of v-model is non-array, then the collection is checked (checked or unchecked, it is a Boolean value)

(2). The initial value of v-model is an array, so what is collected is an array composed of values

Remarks: The three modifiers of v-model:

lazy: lose focus and collect data

number: Convert the input string to a valid number

trim: Input leading and trailing spaces to filter

Commands we have learned:

v-bind: One-way binding parsing expression, which can be abbreviated as: xxx

v-model : two-way data binding

v-for : traverse array/object/string

v-on : Bind to monitor events, which can be abbreviated as @

v-if : conditional rendering (dynamically control whether the node exists)

v-else : conditional rendering (dynamically control whether the node exists)

v-show : conditional rendering (dynamically control whether the node is displayed)

v-text directive:

1. Function: Render text content to the node where it is located.

2. The difference from interpolation syntax: v-text will replace the content in the node, but { {xx}} will not

autofocus: automatically get the focus event

Lifecycle (hook):

Red box: life cycle;

green: links;

 

Life cycle analogy:

Zhang San's life (Zhang San's life cycle):

will be born

(Important) Falling to the ground ===> Check the various indicators of the living body.

learn to speak

learn to walk

··················

··················

(Important) Farewell ===> Confession

farewell

The lifetime of vm (the life cycle of vm):

Will be created ===> call beforeCreate function

Created ===> Call the created function.

Will be mounted ===> call beforeMount function.

(Important) After mounting => call the mount function. ==> [important hook]

1.mounted: send ajax request, start timer, bind custom event, subscribe to message, etc. 【initialization operation】

Will be updated ===> Call the beforeUpdate function.

The update is completed ===> call the update function

(Important) To be destroyed => call the beforeDestroy function. ==> [important hook]

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

Destroyed ===> Call the destroyed function.

components

Definition: A collection of local function codes and resources in an application

Non-single-file components:

A file contains n components

Single file component:

A file contains only one component

Prototype object: js object can be extended through prototype

The implicit prototype object of an instance always points to the prototype object of its creator

 

Three steps to use components in Vue:

1. Define components (create components)

2. Register components

3. Use components (write component tags)

1. How to define a component?

Created using Vue.extend(options), where options are almost the same as the options passed in when new Vue(options), but there are some differences:

The difference is as follows:

1.el do not write, why? ——In the end, all components must be managed by a vm, and the el in the vm determines which container to serve.

2. data must be written as a function, why? —— Avoid data reference relationship when components are reused.

Remarks: Use template to configure component structure.

2. How to register components?

1. Partial registration: pass in the components option when relying on new Vue

2. Global registration: rely on new.component('component name', component)

3. Write component tags:

<school></school>

full version notes

If you have any suggestions, welcome to communicate

Guess you like

Origin blog.csdn.net/m0_62068678/article/details/126822311