官术网_书友最值得收藏!

Data properties

When we add a variable to our data object, we're essentially creating a reactive property that updates the view any time it changes. This means that, if we had a data object with a property named firstName, that property would be re-rendered on the screen each time the value changes:

<!DOCTYPE html>
<html>
<head>
<title>Vue Data</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<h1>Name: {{ firstName }}</h1>
<input type="text" v-model="firstName">
</div>

<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'Paul'
}
});
</script>
</body>
</html>

This reactivity does not extend to objects added to our Vue instance after the instance has been created outside of the data object. If we had another example of this, but this time including appending another property such as fullName to the instance itself:

<body>
<div id="app">
<h1>Name: {{ firstName }}</h1>
<h1>Name: {{ name }}</h1>
<input type="text" v-model="firstName">
</div>

<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'Paul'
}
});
app.fullName = 'Paul Halliday';
</script>
</body>

Even though this item is on the root instance (the same as our firstName variable), fullName is not reactive and will not re-render upon any changes. This does not work because, when the Vue instance is initialized, it maps over each one of the properties and adds a getter and setter to each data property, thus, if we add a new property after initialization, it lacks this and is not reactive.

How does Vue achieve reactive properties? Currently, it uses Object.defineProperty to define a custom getter/setter for items inside of the instance. Let's create our own property on an object with standard get/set features:

 const user = {};
let fullName = 'Paul Halliday';

Object.defineProperty(user, 'fullName', {
configurable: true,
enumerable: true,
get() {
return fullName;
},
set(v) {
fullName = v;
}
});

console.log(user.fullName); // > Paul Halliday
user.fullName = "John Doe";
console.log(user.fullName); // > John Doe

As the watchers are set with a custom property setter/getter, merely adding a property to the instance after initialization doesn't allow for reactivity. This is likely to change within Vue 3 as it will be using the newer ES2015+ Proxy API (but potentially lacking support for older browsers).

There's more to our Vue instance than a data property! Let's use computed to create reactive, derived values based on items inside of our data model.

主站蜘蛛池模板: 宜宾市| 新丰县| 遂溪县| 韶关市| 寿阳县| 乌鲁木齐县| 斗六市| 武胜县| 北辰区| 锦屏县| 阜新市| 昌都县| 金湖县| 普安县| 呼伦贝尔市| 河津市| 胶州市| SHOW| 安顺市| 家居| 新乡市| 平安县| 溧阳市| 桦甸市| 姜堰市| 高唐县| 渑池县| 新田县| 天水市| 青神县| 蓬溪县| 双江| 通道| 祁东县| 双牌县| 怀宁县| 腾冲县| 河西区| 合阳县| 盐源县| 洪江市|