watch和computed

-watch可以单个监听

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div id="app">
        <p>{{ msg }}</p>
        <button @click = 'clickHandler'>修改</button>
    </div>
    <script src="vue.js"></script>
    <script>
        new Vue({
            el:'#app',
            data(){
                return {
                    msg:"alex",
                    age:18
                }

            },
            methods:{
                clickHandler(){
                    this.msg = "wusir"
                }
            },
            watch:{
                //watch单个属性,如果想监听多个属性 声明多个属性的监听
                'msg':function (value) {

                    console.log(value);

                    if (value === 'wusir'){
                        alert(1);
                       this.msg = '大武sir'
                    }
                },
                'age' :function (value) {
                    
                }
            }
        })
    </script>
</body>
</html>
watch单个监听的实例

-计算属性computed监听多个属性

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="app">
    <p>{{ myMsg }}</p>
    <button @click='clickHandler'>修改</button>
</div>
<script src="vue.js"></script>
<script>
    let vm = new Vue({
        el: '#app',
        data() {
            return {
                msg: "alex",
                age: 18
            }

        },
        created() {
            //定时器  ajax  库 function(){}
            setInterval(() => {

            })
        },
        methods: {
            clickHandler() {
                //this的指向就是当前对象
                this.msg = "wusir";
                this.age = 20;
            },
            clickHandler: function () {
                console.log(this);
            }

        },
        computed: {
            myMsg: function () {
                //业务逻辑

//                    计算属性默认只有getter方法
                return `我的名字叫${this.msg},年龄是${this.age}`;
            }
        }
    })

    console.log(vm);
</script>
</body>
</html>
computed

 

posted @ 2018-11-30 12:18  魏三斗  阅读(151)  评论(0编辑  收藏  举报