1. 程式人生 > >watch和computed

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