Vuejs中的methods, computed和watch有何妙用?

百度已收录   阅读次数: 56
2021-10-2415:36:03 发表评论
摘要

继续探索Vuejs的精进用法,有关之前的入门文章,具体可以参看下方的前情提要,本篇文章则是着重来聊一下有关methods,computed和watch这三个概念,从简单到困难一应俱全……

Vuejs中的methods, computed和watch有何妙用?

开篇寄语

继续探索Vuejs的精进用法,有关之前的入门文章,具体可以参看下方的前情提要,本篇文章则是着重来聊一下有关methods,computed和watch这三个概念,从简单到困难一应俱全。

前情提要

内容详情

本篇也是以Vue3版本来示例,与Vue2的版本区别并不算大。

  • method
    • 要向组件实例添加方法,我们使用 methods 选项,这应该是一个包含所需方法的对象,试想一个按钮,按下后,文本数字加1,试举例如下:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>methods demo</title>
</head>

<body>
    <div id="app">
        <p>{{ num }}</p>
        <button @click="addItem">Add</button>
    </div>
    <script src="https://unpkg.com/[email protected]"></script>
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    num: 1,
                }
            },
            methods: {
                addItem() {
                    this.num++
                }
            }
        });
        app.mount("#app")
    </script>
</body>

</html>
  • computed
    • data属性可以传递数据,但是在处理复杂数据的过程中会显得臃肿,此时就需要用到computed属性,那么该属性该如何使用呢?试举一例:
    • computed适用于数据联动
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>methods demo</title>
    <style>
        [v-cloak] {
            display: none;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <button @click="addItem">Add</button>
        <ul>
            <li v-for="(item, index) in list" :key="index">
                <a :href="item.url">{{ item.name }}</a>
            </li>
        </ul>
    </div>
    <script src="https://unpkg.com/[email protected]"></script>
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    num: 1,
                    requestList: [
                        'Google-https://www.google.com',
                        'Github-https://github.com',
                        '行运设计师-https://luckydesigner.space'
                    ]
                }
            },
            computed: {
                list: function() {
                    var list = [];
                    this.requestList.map(function(item, index) {
                        var tempArr = item.split('-');
                        list.push({
                            name: tempArr[0],
                            url: tempArr[1]
                        });
                    })
                    return list;
                }
            },
            methods: {
                addItem() {
                    this.num++;
                    this.requestList.push('行运设计师' + this.num + '-https://luckydesigner.space')
                }
            }
        });
        app.mount("#app")
    </script>
</body>

</html>

除了这种方式外,computed属性还可以设置setter和getter,试举例如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>computed demo</title>
    <style>
        [v-cloak] {
            display: none;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <h2>fullName</h2>
        {{fullName}}
        <h2>firstName</h2>
        {{firstName}}
        <h2>lastName</h2>
        {{lastName}}
    </div>
    <script src="https://unpkg.com/[email protected]"></script>
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    firstName: "Boheng",
                    lastName: "Zhang",
                }
            },
            computed: {
                fullName: {
                    get: function() {
                        return this.firstName + " " + this.lastName
                    },
                    set: function(value) {
                        var list = value.split(' ');
                        this.firstName = list[0]
                        this.lastName = list[1]
                    }
                }
            },
        });
        app.mount("#app")
    </script>
</body>

</html>
  • watch
    • 虽然计算属性在大多数情况下更合适,但有时需要自定义观察器,他可以监听值/表达式的变化来执行回调函数,监听一般只监听一个数量或变化。
    • watch适用于异步场景
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>watch demo</title>
    <style>
        [v-cloak] {
            display: none;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <h2>fullName</h2>
        {{watchFullName}}
        <h2>firstName</h2>
        {{firstName}}
        <h2>lastName</h2>
        {{lastName}}
    </div>
    <script src="https://unpkg.com/[email protected]"></script>
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    firstName: "Boheng",
                    lastName: "Zhang",
                    watchFullName: "Zhang Boheng",
                    age: 18,
                }
            },
            watch: {
                firstName: function(newFirstName, oldFirstName) {
                    this.watchFullName = this.firstName + this.lastName
                },
                lastName: function(newLastName, oldLastName) {
                    this.watchFullName = this.firstName + this.lastName
                }
            },
        });
        app.mount("#app")
    </script>
</body>

</html>
分享至:
  • 我的微信
  • 微信扫一扫加好友
  • weinxin
  • 我的微信公众号
  • 扫描关注公众号
  • weinxin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: