vue计算属性,方法,监听器

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>计算属性,方法,监听器</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>

    <body>
        <div id="app">
            {{fullName}} {{age}}<br /> {{fullNameMethods()}}<br />{{fullName1}}
        </div>
        <script type="text/javascript">
            var vm = new Vue({
                el: "#app",
                data: {
                    firstName: 'Harold',
                    lastName: 'Jim',
                    age: 44,
                    fullName1: '',
                },
                // 计算属性
                computed: {
                    fullName() {
                        console.log("计算属性计算了一次")
                        return "计算属性:" + this.firstName + " " + this.lastName
                    }
                },
                methods: {
                    fullNameMethods() {
                        console.log("方法计算了一次")
                        return "方法:" + this.firstName + " " + this.lastName
                    }
                },
                // 监听
                watch: {
                    firstName(){
                      console.log("监听计算了一次")
                        this.fullName1 = this.firstName + " " + this.lastName;
                    },
                    lastName(){
                      console.log("监听计算了一次")
                        this.fullName1 = this.firstName + " " + this.lastName;
                    }
                }
            })
        </script>
    </body>

</html>

 

getter&&setter

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>计算属性的getter和setter</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>

    <body>
        <div id="app">
            {{fullName}}
        </div>
        <script type="text/javascript">
            var vm = new Vue({
                el: "#app",
                data: {
                    firstName: 'Harold',
                    lastName: 'Jim',
                },
                // 计算属性
                computed: {
                    fullName: {
                        get() {
                            return "计算属性:" + this.firstName + " " + this.lastName
                        },
                        set(value) {
                            let arr = value.split(" ")
                            this.firstName = arr[0]
                            this.lastName = arr[1]
                            console.log("setter:" + value)
                        }
                    }
                },
            })
        </script>
    </body>

</html>

 

posted @ 2019-10-22 15:07  嘆世殘者——華帥  阅读(146)  评论(0编辑  收藏  举报