数据的响应性
参考内容:
Vue 中存在以下三种数据:
data: 组件内部的数据props: 外部传入的数据computed: 计算数据
数据具有响应性,具体表现在以下几个方面:
1. 模板渲染
模板不是只在组件初始化时渲染一次,而是会在数据发生变化后重新渲染:
<template> <p>now: {{ now }}</p> <p>datetime: {{ formatDateTime(now) }}</p></template>
<script>export default { name: 'DemoClock', data() { this.timer = null;
return { now: new Date(), }; }, mounted() { this.timer = window.setInterval(() => { this.now = new Date(); }, 1000); }, beforeUnmount() { if (this.timer) { window.clearInterval(this.timer); } }, methods: { formatDateTime(time) { return time.toLocaleString(); }, },};</script>组件逻辑:
data中声明了数据now,用于保存当前时间- 模板中使用了
{{ now }}和{{ formatDateTime(now) }} mounted()事件中启动了定时器,每秒更新一次nowbeforeUnmount()事件中清除了定时器
运行后可以发现页面中的两行文字每秒钟都会更新一次。
Vue 会在 now 数据发生变化后,检查模板中对 now 的每一处引用,完成计算并决定是否重新渲染。
2. 关联方法
computed 中的方法及模板中调用的方法会在依赖的数据发生变化后自动重新执行。
3. 数据绑定
如果组件中的数据通过模板绑定到子组件,当数据发生变化后,子组件的 props 数据也会更新。