vue filters and listeners and computed properties

1. Filter

1.1 basic usage

Filters are a function provided by vue for developers and are often used for text formatting. Filters can be used in two places: interpolation expressions and v-bind attribute bindings.

The filter should be added at the end of the Javascript expression and called by the pipeline character |:

  • Format the value by calling the filter in curly braces

    <p>message: {{ message | capi }} </p>
    
  • Definition of capi filter

    • Defined under filters, it is essentially a function
    • In the parameters of the filter, there must be a return value
    • In the formal parameters of the filter, you can obtain the pending value before |
    const vm = new Vue({
        el: '#app',
        data: {
        	message: 'hello Vue !'
        },
        // Define filter functions
        filters:{
            capi(val) {
                // Formal parameter before val filter | value before val filter
                // charAt receives the index value and returns the corresponding character
    
                const first = val.charAt(0).toUpperCase()
                const other = val.slice(1)
                return first + other
            }
        }
    })
    

1.2 private and global filters

The filter defined in the filters node is called "private filter" because it can only be used in the el area controlled by the current vm instance. If you want to share filters among multiple vue instances, you can define global filters in the following format:

  • The global definition is placed before the vm instance
  • The filters in the filters of the vm instance are preferred
  • If the filters of the vm instance do not have relevant filters, the global filter is used
  • If there is neither private nor global, use the prototype
// Vue. The filter () method receives two parameters:
// First parameter: the name of the global filter
// Second parameter: Global filter processing function
Vue.filter('capi' , (val) => {
    const first = val.charAt(0).toUpperCase()
    const other = val.slice(1)
    return first + other
})

1.3 Dayjs

Day.js is a minimalist JavaScript library that can parse, verify, operate and display date and time for modern browsers.

Official website: Day.js Chinese website (fenxianglu.cn)

Usage details: Official Website = > document = > analysis

<td>{{ item.time | dataFormat}} </td>
// Global filter for declaring formatting time
Vue.filter('dataFormat' , (time) => {
    // YYYY-MM-DD HH:mm:ss
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss');  
})

1.4 call multiple filters continuously

Filters can be called in series:

{{ message | filterA |  filterB |filterC }}

1.5 filter transmission parameters

The filter is essentially a JavaScript function, so it can accept parameters:

{{ message | filterA(arg1 , arg2)}}
Vue.filter('filterA' , (msg , arg1 , arg2) => {
    // code...
})

1.6 compatibility

vue3 is not supported.

2. watch listener

2.1 introduction

The watch listener allows developers to monitor the changes of data, so as to do specific operations for the changes of data.

const vm = new Vue({
    el: '#app',
    data: {
        message: 'hello Vue !'
    },
    // Define listener
    // If you want to monitor the change of which data, you can take this data as the method name
    watch: {
        message(newMes , oldMes){
            console.log(newMes , oldMes)
        }
    }
})

2.2 application scenario: judge whether the user name is occupied

<body>
    <div id="app">
        <input type="text" name="" id="" v-model="username"><span>{{ message}}</span>
    </div>

    <script src="./lib/vue.js"></script>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        // Vue. The filter () method receives two parameters:
        // First parameter: the name of the global filter
        // Second parameter: Global filter processing function
        Vue.filter('capi' , (val) => {
            const first = val.charAt(0).toUpperCase()
                    const other = val.slice(1)
                    return '123'
        })
        // Create vue instance object
        const vm = new Vue({
            el: '#app',
            data: {
                username: 'zhangsan',
                message: ''
            },
            // Define listener
            // If you want to monitor the change of which data, you can take this data as the method name
            watch: {
                username(newName , oldName){
                    $.get('https://www.escook.cn/api/finduser/' + newName , function(result){
                        vm.message = result.message
                        console.log(result)
                    })
                }
            }
        })
        
    </script>
</body>

2.3 immediate option

  • Method format listener
    • Disadvantage 1: it cannot be triggered automatically when you first enter the page
    • Disadvantage 2: if listening to an object, the change of object attribute value will not trigger the listener!
  • Object format listener
    • Benefit 1: the listener can be triggered automatically through the immediate option
    • Benefit 2: you can monitor the changes of each attribute in the object through the deep option
watch: {
    // Listener that defines the format of the object
    username: {
        //  handler listener processing function
        handler(newName , oldName) {
            $.get('https://www.escook.cn/api/finduser/' + newName , function(result){
                vm.message = result.message
                console.log(result)
            })
        },
            // If immediate is true, it will be triggered automatically once, and the default is false
            immediate: true
    }
}

2.4 deep option

  • Listener in object format: you can listen for the change of each attribute in the object through the deep option
  • If you want to listen for changes in the sub attributes of an object, you need to add single quotes: info username() {...}
<div id="app">
    <input type="text" name="" id="" v-model="info.username"><span>{{ message}}</span>
</div>
const vm = new Vue({
    el: '#app',
    data: {
        info: {
            username: 'admin'
        },
        message: ''
    },
    // Define listener
    // If you want to monitor the change of which data, you can take this data as the method name
    watch: {
        info: {
            //  handler listener processing function
            handler(newObj , oldObj) {
                $.get('https://www.escook.cn/api/finduser/' + newObj.username , function(result){
                    vm.message = result.message
                    console.log(result)
                })
            },
            // If immediate is true, it will be triggered automatically once, and the default is false
            immediate: true,
            // Enable deep listening. The default value is false
            deep: true
        }
    }
})

3. Calculation attribute

3.1 understand the application scenarios of calculation attributes

Calculating attributes refers to obtaining an attribute value after a series of operations.

The dynamically calculated attribute value can be used by the template structure or methods method.

  • All calculation attributes are defined under the calculated node
  • Calculation properties should be defined in the form of methods
  • When using the calculation attribute, it can be used as the attribute of vm
computed:{
    // Returns the generated rgb(x,x,x) string
    rgb() {
        return `rgb(${this.r},${this.g},${this.b})`
    }
}

3.2 cases of controlling div background color

Benefits:

  • Code reuse is realized
  • As long as the dependent data source changes, the calculated attribute is re evaluated
<style>
    #app{
        margin: 100px;
    }
    .box{
        width: 200px;
        height: 200px;
    }
</style>
<div id="app">
    <p>r: <input type="text" v-model.number="r"> </p>
    <p>g: <input type="text" v-model.number="g"> </p>
    <p>b: <input type="text" v-model.number="b"> </p>
    <div class="box" :style="{ backgroundColor:rgb}">
        {{  rgb }}
    </div>
    <button @click="show">Button</button>
</div>
const vm = new Vue({
    el: '#app',
    data: {
        r: 0,
        g: 0,
        b: 0
    },
    computed:{
        // Returns the generated rgb(x,x,x) string
        rgb() {
            return `rgb(${this.r},${this.g},${this.b})`
        }
    },
    methods: {
        // Click the button to display the color on the terminal
        show() {
            console.log(this.rgb)
        }
    }
})

Keywords: Javascript Front-end Vue Vue.js

Added by gmwebs on Thu, 17 Feb 2022 15:30:20 +0200