Vue的计算属性和watch监听

1.

<body>
    <div id="app">
        <h1>您的生日是:{{
            new Date(birthday).getFullYear() + '-'+ new Date(birthday).getMonth()+ '-' + new Date(birthday).getDay()
            }}
        </h1>
        <h1>您的生日是:{{birth()}} </h1>
        <h2>{{name}},非常帅!!!</h2>
    </div>
</body>
<script src="node_modules/vue/dist/vue.js" ></script>
<script>
    // 创建vue实例
    var app = new Vue({
        el:"#app", // el即element,该vue实例要渲染的页面元素
        data:{ // 渲染页面需要的数据
            name: "峰哥",
            birthday:1529032123201 // 毫秒值
        },
        methods:{
            birth(){// 计算属性本质是一个方法,但是必须返回结果
                const d = new Date(this.birthday);
                return d.getFullYear() + "-" + d.getMonth() + "-" + d.getDay();
            }
        }
    });

</script>

2.计算属性

计算属性本质就是方法,但是一定要返回数据。然后页面渲染时,可以把这个方法当成一个变量来使用。

computed:{
    birth2(){// 计算属性本质是一个方法,但是必须返回结果
        const d = new Date(this.birthday);
        return d.getFullYear() + "-" + d.getMonth() + "-" + d.getDay();
    }
}
<h1>您的生日是:{{birth2}} </h1> 这个时候不用加括号表示函数

3.watch监听

<div id="app">
    <input type="text" v-model="message">
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el:"#app",
        data:{
            message:""
        },
        watch:{
            message(newVal, oldVal){
                console.log(newVal, oldVal);
            }
        }
    })
</script>

发布了52 篇原创文章 · 获赞 74 · 访问量 6358

猜你喜欢

转载自blog.csdn.net/qq_39182939/article/details/105003564