Vue calculates the get and set methods of attribute computed

Let's look at a simple example

<body>
    <div id="app">
        {
    
    {
    
    fullName}}
    </div>
    <script>
        var vm = new Vue({
    
    
            el: '#app',
            data: {
    
    
                firstName: 'wade',
                lastName: 'dean'
            },
            computed: {
    
    
                fullName: function() {
    
    
                    return this.firstName + ' ' + this.lastName
                }
            }
        });
    </script>
</body>

Undoubtedly, the effect is as follows:
Insert picture description here

We can set an object for the fullName in the calculated property, which contains get and set methods:

<body>
    <div id="app">
        {
    
    {
    
    fullName}}
    </div>
    <script>
        var vm = new Vue({
    
    
            el: '#app',
            data: {
    
    
                firstName: 'wade',
                lastName: 'dean'
            },
            computed: {
    
    
                fullName: {
    
    
                    get: function () {
    
    
                        console.log('running get function')
                        return this.firstName + ' ' + this.lastName
                    },
                    set: function (value) {
    
    
                        console.log('running set function')
                        var arr = value.split(' ')
                        this.firstName = arr[0]
                        this.lastName = arr[1]
                    }
                }
            }
        });
    </script>
</body>

After the program runs, the console prints running get function, indicating that the get method of fullName is called at the beginning.
Insert picture description here
We manually modify the value of fullName in the console: at
Insert picture description here
this time, the fullName is modified, so call the set method, print the running set function, and put amanda And zhao are assigned to firstName and lastName respectively. Vue detects that the firstName and lastName on which fullName is calculated has been modified, so it triggers the get method again, prints the running get function, and renders the calculated new fullName value to the page

Guess you like

Origin blog.csdn.net/dyw3390199/article/details/112387792