Vue study notes-two: Vue common features

Common features of Vue

Form operation

Vue-based form operation

  • input single line of text
    • Two-way binding through v-model
  • textarea multi-line text
  • select drop-down multiple selection
  • radio radio
  • checkbox checkbox

Form field modifier

  • number: converted to a numeric value (default is a string)
  • trim: remove the spaces at the beginning and end
  • lazy: switch input event to change event
 <div id="app">
        <!-- <input type="text" name="" id="" v-model="age"> -->
        <input type="text" v-model.number='age'>
        <input type="text" v-model.trim='trimc'>
        <input type="text" v-model.lazy='changet'>
        <div>{
    
    {
    
    changet}}</div>
        <input type="submit" value="点击" @click="handle">
    </div>
    <script>
        let vm = new Vue({
    
    
            el:"#app",
            data: {
    
    
                age: '',
                trimc: '',
                changet: ''
            },
            methods: {
    
    
                handle(){
    
    
                    console.log(this.age);
                    console.log(this.trimc);
                    console.log(this.changet);
                }
            }
        });
    </script>

Custom instruction

  1. Why do you need custom instructions

    Built-in instructions do not meet the demand

  2. Syntax rules for custom instructions (get element focus)
    Vue.directive('focus' ,{
         inserted: function(el){
             //获取元素的焦点
             el.focus();
         }
     })
    
  3. Custom instruction usage
<div id="app">
        <input type="text" v-focus>
    </div>
    <script>
        Vue.directive('focus' ,{
    
    
            inserted: function(el){
    
    
                //获取元素的焦点
                el.focus();
            }
        })
        let vm = new Vue({
    
    
            el:"#app",
            data: {
    
    },
            methods: {
    
    }
        });
    </script>
Hook function parameters
  • el: The element bound by the instruction, which can be used to directly manipulate the DOM
  • binding: an object that contains:
    • name: command name, excluding v-, prefix
    • value: the binding value of the instruction,
    • oldValue: the previous value bound by the instruction
Local instruction

Add an additional instruction.

directives: {
	focus: {
		//指令的定义
		inserted: function(el){
			el.focus()
		}
	}
}

Calculated attributes

The calculation logic of the expression may be more complicated, and the use of calculated attributes can make the template content more concise

computed:{
	reversedMessage: function(){
		return this.msg.split('').reverse().join('')
	}
}
The difference between calculated properties and methods
  • Computed attributes are cached based on their dependencies
  • Method does not exist in cache
<div id="app">
        <input type="text" v-model="msg" name="" id="">
        <div>{
    
    {
    
    reversed}}</div>
    </div>
    <script>
        let vm = new Vue({
    
    
            el:"#app",
            data: {
    
    
                msg:""
            },
            methods: {
    
    },
            computed:{
    
    
                reversed: function(){
    
    
                    return this.msg.split('').reverse().join('');
                }
            }
        });
    </script>

filter

The role of filters

Format data, such as formatting a string to capitalize the first letter, and convert the date format to a specified format.

Definition of filter
Vue.filter('过滤器名称', function(value){
	//过滤器业务逻辑
}
Use of filters
//upper:过滤器得名称 
<div>{
   
   {msg | upper}}</div>
<div>{
   
   {msg | upper | lower}}</div>
<div v-bind:id | formatId></div>
Local filter
filters:{
	capitalize: function(){}
}
<div id="app">
        <input type="text" v-model="msg">
        <div>{
    
    {
    
    msg | upper}}</div>
        <div>{
    
    {
    
    msg | upper | lower}}</div>
        <div :upp="msg | upper" >{
    
    {
    
    msg}}</div>
    </div>
    <script>
        Vue.filter('upper', function(val){
    
    
            return val.toUpperCase();
        });
        Vue.filter('lower', function(val){
    
    
            return val.toLowerCase();
        })
        let vm = new Vue({
    
    
            el:"#app",
            data: {
    
    
                msg: ''
            },
            methods: {
    
    },
        });
    </script>

Listener

The listener is used to monitor data, and when the data changes, it will notify the method bound to the listener

Application scenarios

Perform asynchronous or expensive operations when data changes

(There are similarities with calculated attributes)

watch: {
	//方法,val表示当前数据的最新值
	firstName: function(val){
		this.fullName = val + this.lastName;
	},
	lastName: function(val){
		this.fullName = this.firstName + val;
	}
}
Case study

Verify that the username is available

Requirement: Enter the name in the input box and verify whether it exists when the focus is lost. If it already exists, the prompt will be re-entered, if it does not exist, the prompt can be used.

operating:

1. Realize data binding through v-model

2. Reminders need to be provided

3. A listener is required to monitor changes in input information

4. Need to modify the triggered event

<div id="app">
        用户名:<input type="text" v-model.lazy="msg">
        <div>{
    
    {
    
    tip}}</div>
    </div>
    <script>
        let vm = new Vue({
    
    
            el: "#app",
            data: {
    
    
                msg: '',
                tip: ''
            },
            methods: {
    
    
                checkname: function (uname) {
    
    
                    //调用接口,可用定时任务模拟接口调用
                    let that = this;
                    setTimeout(function () {
    
    
                        //模拟接口调用
                        if (uname == 'admin') {
    
    
                            that.tip = '用户名已经存在'
                        }else{
    
    
                            that.tip = '可以注册'
                        }
                    },2000)
                }
            },
            watch: {
    
    
                msg: function (val) {
    
    
                    //调用后台接口验证用户名的合法性
                    this.checkname(val);
                    this.tip = "正在验证。。。"
                }
            }
        });
    </script>
Listener

1. Use a listener to monitor user name changes

2. Call the background interface for verification

3. Adjust the prompt information according to the verification result

Life cycle (life cycle hook function)

Main stage
  • Mount (initialize related properties)
    1. beforeCreate
    2. created
    3. beforeMount
    4. mounted
  • Update (change operation of element or component)
    1. beforeUpdate
    2. updated
  • Destroy (destroy related attributes)
    • beforeDestroy
    • destroyed
<div id="app">
        <input type="text" name="" id="" v-model="msg">
        <button @click="destroy">销毁</button>
    </div>
    <script>
        let vm = new Vue({
    
    
            el:"#app",
            data: {
    
    
                msg: ""
            },
            methods: {
    
    
                destroy: function(){
    
    
                    this.$destroy();
                }
            },
            beforeCreate() {
    
    
                console.log("beforeCreate...");
            },
            created() {
    
    
                console.log("create...");
            },
            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>

Life cycle diagram

[Picture from official website]
Insert picture description here

Destroying is to release some resources

mounted: indicates that the initialization has been completed and the template already exists.

The process of generating Vue instances
  • beforeCreate is called after the instance is initialized and before the data observation and event configuration
  • created is called immediately after the instance is created
  • beforeMount is called before the start of the mount
  • The mounted el is replaced by the newly created vm.$el, and the example is called after it is mounted on the instance
  • beforeUpdate is called when the data is updated, which occurs before the virtual DOM is patched
  • updated virtual DOM re-rendering and patching due to data changes, call after this
  • beforeDestroy is called before the instance is destroyed
  • Called after the destroyed instance is destroyed

Guess you like

Origin blog.csdn.net/leilei__66/article/details/115103398