VUE2 basic knowledge study notes

VUE2

template syntax

The content of the tag body uses the difference syntax, and the attribute uses: (v-bind:) which is the instruction syntax

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-G8COcV8F-1662560470884) (C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\ image-20220825203807795.png)]

Syntax in Vue instantiation

Two methods of data binding

  1. v-bind single item data binding

    Abbreviated as : value="name"

  2. v-mode l double item data binding

​ Can only be applied to form class elements (input class, with value)

​Abbreviated as v-model="name"

Two methods of binding container el

  1. Specify at the beginning of new

    new vue({
          
          
        el:"#root",
        data:{
          
          }
    })
    
  2. I didn't know it at first, but added

    const x = new vue({
          
          
        data:{
          
          }
    })
    x.$mount("#root")
    

Two ways of writing data

  1. Object style (let's not talk about it)

  2. Functional style (this must be used for components)

    data:function(){
          
          //不能用箭头函数
        return{
          
          
            name:"sss"
        }//返回值是我需要的函数
    }
    
    //可以简写
    data(){
          
          //不能用箭头函数
        return{
          
          
            name:"sss"
        }//返回值是我需要的函数
    }
    

Method in Vue instance

new vue({
    
    
    el:"#root",
    data:{
    
    },
    
    methods:{
    
    
        xxx(e){
    
    
            ...
        }
    }
})
  • This in methods points to vm or component instance object

Data proxy (Object.defineProperty())

let num = 18;
let person={
    
    
    name:"55",
    sex:"男"
}


//数据代理雏形
Object.defineProperty(person,"age",{
    
    
//    value = 18,
    //enumerable:false,
    //configurable:false,
    //writable:false,
    //以上三个默认值都是false
    
    get(){
    
    
        log(...)
            return num  //把这个变量当做值
    },
    
    set(value){
    
    
        log(...)
        num=value   //!!!!!!!没有这一步可是没法绑定着一起改值
    }
})

command syntax

Two methods of data binding

  1. v-bind single item data binding

    Abbreviated as : value="name"

  2. v-mode l double item data binding

​ Can only be applied to form class elements (input class, with value)

​Abbreviated as v-model="name"

event handling

####1. Click event binding

<button v-on:click="show">点我</button>

Short form:

<button @click="show">点我</button>

​ If the function needs to pass parameters

<button @click="show($event,66)">点我</button>
//$event代表e 如果要用=>就这样占个位
			 不用的话=>可以省略

insert image description here

2. Event modifiers

  • Can write continuously
    • 例1:@click.stop.prevent=“show”
    • Example 2: Detect key combination: @keyup.ctrl.y="show"
//阻止默认行为(常用)
<button @click.prevent="show($event,66)">点我</button>

//阻止冒泡(常用)
<button @click.stop="show($event,66)">点我</button>

//事件只触发一次(一次性事件)(常用)
<button @click.once="show($event,66)">点我</button>

//事件捕获模式
<button @click.capture="show($event,66)">点我</button>

//只有e.target是当前操作的元素才触发事件
<button @click.self="show($event,66)">点我</button>

//事件默认行为立即执行,无需等待事件回调执行完毕
<button @click.passive="show($event,66)">点我</button>

####3. Scrollbar event binding

<div @scroll="show">滚我</div>

####4. Mouse wheel event binding

<div @wheel="show">滚我</div>

####5. Keyboard event binding

<input @keyup="show">输入</input>
<input @keydown="show">输入</input>


//按下某按键触发(别名)
<input @keyup.enter="show">输入</input>

insert image description here

insert image description here

Monitor properties

//第一种监视属性写法(适用于一开始就确定要监视什么)
const vm = new vue({
    
    
    el:"#root",
    data:{
    
    },
    methods:{
    
    },
    
    watch:{
    
    
        xxx:{
    
    
            deep:true,//开启多层级监测所有属性
            immediate:false,
            handler(newvalue,oldvalue){
    
    
                log...
            }
                
        "num.a"{
    
    }//监视多级结构某个属性的变化
        }
    }
        
})
    
//第二种监视属性写法(适用于一开始不确定要监视什么)
    vm.$watch("xxx",{
    
    
    	immediate:false,
    	handler(newvalue,oldvalue){
    
    
    		...
	}
})

### Monitor attribute shorthand

(It can be abbreviated without other configuration items, only handler)

watch:{
    
    
    isHot(newValue,oldValue){
    
    
        ...
    }
}
    
//第二种
    vm.$watch("...",function(newValue,oldValue){
    
    
        ...
    })

conditional rendering

"Boolean value/expression that converts to a Boolean value"

1. v-show=“”

2. v-if=“”

v-else-if=“”

v-else>

  • and not allowed to be interrupted
  • Can cooperate with template without affecting the final structure

list rendering

v-for=“(value,index in xxx)”

  • the list
  • object
  • string
  • specified number of cycles

insert image description here

The principle of key

Interview question: What is the function of key in vue?

insert image description here

Vue monitoring principle

Add monitorable data after

Vue.set()

vm.$set()

insert image description here
insert image description here

Built-in instructions (important)

insert image description here

###1. v-text

Does not support structure parsing approximately equal to innerText

2. v-html

Support structure parsing approximately equal to innerHtml

3. v-cloak

  • is a special attribute with no value

  • Will be deleted when vue takes over

  • can be used with css

    [v-cloak]{
          
          
        display:none
    }
    

4. v-once

  • After the initial dynamic rendering, it is regarded as static data and will not change

5. in-for

  • Vue does not compile
  • Code that does not need to be compiled can be skipped to improve performance

6. Custom directives

  • The this in the custom command is window

  • When will the custom directive be called?

    1. When the directive is successfully bound to the element (at the beginning)
    2. When the template containing the directive is reparsed
  • Functional

    • insert image description here

    • new Vue({
              
              
          el:"#root",
          data:{
              
              
              name:"hhh",
              n:1
          },
          directives:{
              
              
              big(ele,bingding){
              
              
                  ele.innerText = bingding.value*10
              }
          }
      })	
      
  • object style

    • new Vue({
              
              
          el:"#root",
          data:{
              
              
              name:"hhh",
              n:1
          },
          directives:{
              
              
              big:{
              
              
                  bind(ele,binding){
              
              
                      //元素绑定时
                  },
                  inserted(ele,binding){
              
              
              //元素放入页面时
          },
          update(ele,binding){
              
              
              //绑定元素更新时
          }
          
              }
          }
      })	
      
  • Summarize

    • insert image description here

Life cycle (important)

1. Icon

insert image description here

  • Summarize
    • insert image description here

Component Important Properties

render function

  • Used in scaffolding, because the imported vue is a simplified version without a template compiler

  • render:h=>h(App)
    
    
    //用来代替以下两行
    //<template><App></App></template>
    //components:{App}
    

Modify the default configuration of scaffolding

  • Configuration of entry files, syntax checking, etc.
  • It can be modified with the vue.config.js file by querying the official document

ref attribute

  • Used as a substitute for id to get the element

  • The real dom element is obtained when used on the html element, and the component instance object (vc) is obtained when used on the component element

  • How to use: mark first, then get

    • <h1 ref="title">
          你好
      </h1>
      
    • console.log(this.$refs.title)
      

props configuration

  • Function: Let the component accept data from the outside

  • use:

    • pass data

      <SchoolMsg name="xxx" age="18"></SchoolMsg>
      
      //传递的都是字符型,要传递数字型,则:加冒号
      <SchoolMsg name="xxx" :age:"18"></SchoolMsg>
      
    • There are three ways to receive data:

        1. Simply accept, no limit

          methods:{
                      
                      },
          props:["name","age"]
          
        1. restriction type

          props:{
                      
                      
              name:String,
              age:Number
          }
          
        1. Complete writing, limit type, limit necessity, specify default value

          props:{
                      
                      
              name:{
                      
                      
                  type:String,
                  requirea:true
              },
              age:{
                      
                      
                  type:Number,
                  default:99
              }
          }
          
  • Note: The props attribute is read-only, and the bottom layer of Vue will detect it and prevent you from modifying it. If you want to modify, you can back up the data to be modified to data, and then modify the data of data

    //备份
    data(){
          
          
        return{
          
          
            myName:this.name
        }
    }
    

mixedin

  • Essence : In fact, it is code reuse, which extracts the common code configuration of multiple components into a mixed-in object

  • Instructions:

    • define mix

      • New mixin.js

      • Write public configuration

        export const mixin = {
                  
                  
            data(){
                  
                  },
            methods:{
                  
                  }
        }
        
        export const mixin2 = {
                  
                  
            data(){
                  
                  },
            methods:{
                  
                  }
        }
        
    • Introduce and use

      • Global mixins:

        import {
                  
                  mixin,mixin2} from './xxx/mixin.js'
        Vue.mixin(xxx)
        
      • Partially mixed in:

        import {
                  
                  mixin} from './xxx/mixin.js'
        mixins:[xxx]
        

vue plugin (Plugins.js)

  • Essence: an object containing the install method, the first parameter is Vue, and the second parameter is the data passed by the plug-in user

    export default{
          
          
        install(Vue){
          
          
            ...
            //1. 添加全局过滤器
            Vue.filter("过滤器名字",function(val){
          
          
                return val.xxxxxx
            })
            
           //2. 添加全局指令
            Vue.derective("指令名",{
          
          
                bind(ele,bingding){
          
          
                    ...
                    ele.value = bingding.value
                },
                inserted(ele,binding){
          
          
                    ...
                },
                    updata(ele,binding){
          
          
                        ...
                    ele.value = bingding.value
                    }
            })
            
            //3.配置全局混合
            Vue.mixin({
          
          
                //例:
                data(){
          
          
                return{
          
          
                    ...
                }
            }
            })
                      
            //4.添加实例方法
            Vue.prototype.$myMethods=function(){
          
          ...}
            Vue.prototype.$myPrototype = xxx
                                                		Vue.prototype.hello=()=>{
          
          alert("555")}
        }
    }
    
  • use:

    import Plugins from './.../Plugins.js'
    Vue.use(插件名)
    

scoped

  • Function: Prevent multi-component class name conflicts

  • use:

    <style scoped>....</style>
    

Component custom events (for child to parent)

to bind

  • The first @/v-on method

    <student @zidingyi="demo(这个就是你要回调的函数)"/>
    
    methods:{
          
          
    	demo(name){
          
          
    		console.log("我收到了某个数据:" +name)
    	}
    }
    

    student component

    //<button @click="chufa">点击触发自定义事件</button>
    methods:{
          
          
        chufa(){
          
          
            this.$emit("zidingyi",this.name)//this.name就是我要传的参数,可传递多个,实现子传父
        }
    }
    
  • The second ref method

    <student ref="student"/>
    
    mounted(){
          
          
        this.$refs.student.$on("zidingyi",this.demo)
        //this.$refs.student.$once("zidingyi",this.demo)
        
        //this.demo  要么在父组件中配置好,要么直接回调使用箭头函数,否则this指向会出问题(指向emit他的组件)
    }
    

    student component

    //<button @click="chufa">点击触发自定义事件</button>
    methods:{
          
          
        chufa(){
          
          
            this.$emit("zidingyi",this.name)//this.name就是我要传的参数,可传递多个,实现子传父
        }
    }
    

untie

jiebang(){
    
    
    this.$off("zidingyi")//解绑zidingyi
    this.$off(["zidingyi","zidingyi"])//解绑两个
    this.$off()//全部解绑
    this.$destroy()//销毁this组件,与之相关的自定义事件全部解绑
}

Components bind native dom events

The native modifier is required, otherwise the component will consider it a custom event

<demo @click.native="show"></demo>

Component global event bus (important)

  • Suitable for communication between arbitrary components

  • Install the global time bus

    new Vue({
          
          
        ...
        beforeCreate(){
          
          
        	Vue.prototype.$bus=this
    	},
        ...
    })
    
  • Using the event bus

    1. Accept data, a wants to receive data, then a binds a custom event to the bus

      methods:{
              
              
          demo(data){
              
              
              console.log("我收到了:"+data)
          }
      },
         mounted(){
              
              
             this.$bus.$on("zidingyi",this.demo)
         }
      
    2. Components that provide data, trigger custom events, and transmit the data to be sent at the same time

      //在某个函数中可写
      this.$bus.$emit("zidingyi",要传的数据xxx)
      
  • unbind event

    • It is best to use the beforeCreate hook to unbind the event in component a bound to the custom event

      ...
      beforeCreate(){
              
              
          this.$bus.$off("zidingyi")
      }
      ...
      

Message Subscription and Publishing (pubsub-js)

  • Install: npm i pubsub-js

  • use:

    1. Receive data (subscribe message), if a wants to receive data, then a subscribes a message to bus
    import pubsub from 'pubsub-js'
    
    methods:{
          
          
        demo(msgName,data){
          
          
            console.log("我收到了:"+data)
        }
    },
       mounted(){
          
          
           	this.pubId=pubsub.subscribe("hello",this.demo)
           this.pubId=pubsub.subscribe("hello",(msgName,data)=>{
          
          
               ...
           })
       }
    
    1. Components that provide data, trigger custom events, and transmit the data to be sent at the same time

      import pubsub from 'pubsub-js'
      //在某个函数中可写
      pubsub.publish("hello",要传的数据xxx)
      
    2. unsubscribe

      It is best to use the beforeCreate hook to unbind the event in the component a that has subscribed to the message

           ...
           beforeCreate(){
              
              
               pubsub.unsubscribe(this.pubId)
           }
           ...
      

$nextTick hook (important)

  • grammar:

    this.$nextTick(function(){
          
          
        ...
    })
    
  • Function: execute the callback after the next dom update

  • When to use: After changing the data, you want to do some operations based on the updated new dom, then perform those operations in this hook

animation

Instructions

single element

  • Wrap the elements to be animated with

    <transition name="hello" appear>
    	<h1 (v-show..条件)>
            你好
        </h1>
    </transition>
    
    <!--appear  用于一开始直接有动画,不用触发-->
    
  • ready style

    //准备动画
    @keyframe animate{
          
          
        0%{
          
          
            transform:translateX(-100%)
        }
        100%{
          
          
            transform:translateX(0px)
        }
    }
    
    //进入动画 name/v-enter-active
    .hello-enter-active{
          
          
        animation:animate 1s linear
    }
    
    //退出动画 name/v-leave-active
    .hello-leave-active{
          
          
        animation:animate 1s linear reverse
    }
    

multiple elements

  • Use the package, add a key to each element inside

animate.css library

use:

import 'animate.css'
<transition 
            name="animate__animated animate__bounce"
            enter-active-class="xxx"
        	leave-active-class="xxx"
>
	<h1 (v-show..条件)>
        你好
    </h1>
</transition>

slot slot

single slot

  • basic use

    1. component student
    <template>
    	<div>
        	<p></p>
            <slot></slot>
        </div>
    </template>
    

    2. Parent component app

    ​ Can show two effects with the same component

    <template>
    	<div>
            <student><button></button></student>
            <student><p></p></student>
        </div>
    </template>
    
  • Default Display

    • Where subcomponents go in slots...

      <slot><button></button></slot>
      
    • When a parent component uses a child component

       <!-- 什么都没写默认插入button-->
      <student></student>
       <student></student>
      
       <!-- 写了p,那就把butto替换成p-->
      <student><p></p></student>
      

use multiple slots

  • Named slots (template only)

    subcomponentstudent

    <template>
    	<div>
            <slot name="left"></slot>
            <slot name="center"></slot>
            <slot name="right"></slot>
        </div>
    </template>
    

    Parent component (replace only the slot in the middle) (replace two at the same time wrapped in template)

    <template>
    	<student v-slot="center">
            <p >哈哈哈哈</p>
        </student>
    </template>
    
    
    
    <template>
    	<student >
            <template v-slot="center">
                <p >哈哈哈哈</p>
            </template>
            
            <template v-slot="right">
                <p >哈哈哈哈</p>
            </template>
        </student>
    </template>
    

The data of the child component is passed from the child to the parent through the slot

subcomponentstudent

<template>
	<div>
        <slot :data="data" name="default">
        	{
   
   {data.name}}
        </slot>
    </div>
</template>

parent component

<template>
	<student>
        <template v-slot:default="data">//当只有一个slot时,defalut可以省略
            {
   
   {data.sex}}		
        </template>
    </student>
</template>

Guess you like

Origin blog.csdn.net/weixin_46466212/article/details/126755185