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

What is reactivity?

To grasp the concept better, let's look at an example code in which there is no reactivity. We will use an example that is very similar to the one we had in the previous chapter, when we were comparing Vue and vanilla JS. In the original example, using JavaScript, we created an unordered list and three list items inside of it. The values of the three list items were added from an array we declared, and the unordered list was populated with these list items using a for loop.

This time, we will do something slightly different. To see the example as a pen, visit https://codepen.io/AjdinImsirovic/pen/JZOZdR

In this non-reactive example, we are predefining the members of the array as variables. Then we populate the array with those variables and print them to the screen as list items of an unordered list that gets appended to the document:

var a = 1;
var b = a + 1;
var c = b + 2;
var arr1 = [a,b,c];
var unorderedList = document.createElement('ul');
document.body.appendChild(unorderedList);
for (var i=0; i<3; i++) {
var listItem = document.createElement('li');
listItem.className = "list-item";
unorderedList.appendChild(listItem);
listItem.innerHTML = arr1[i];
}
arr1[0] = 2;
for (var i=0; i<3; i++) {
var listItem = document.createElement('li');
listItem.className = "list-item";
unorderedList.appendChild(listItem);
listItem.innerHTML = arr1[i];
}

However, what happens when we change a member of the array and repeat the for loop a second time? As we can see in the pen, the first and the fourth list items are different. The first value is 1, and the second value is 2. To make it more obvious, these items are in bold red text and have a gray background. The first value is the initial value of var a. The second value is the value of var a, updated with this line of code: arr1[0] = 2.

However, the values of variables b and c are not updated in the second for loop, even though we defined variables b and c in terms of variable a increased by 1 and 2, respectively.

So, we can see that there is no reactivity in JavaScript out of the box.

As far as Vue is concerned, reactivity is the term that is used to refer to the way in which Vue tracks changes. In other words, reactivity is the way in which changes in state are reflected in the DOM. Practically, this means that when a change is made to data, that change will be propagated to the page so that the user can see it. Therefore, saying that Vue is reactive is the same as saying Vue tracks changes. As a concept, it's as simple as that.

主站蜘蛛池模板: 孟津县| 尚志市| 台南市| 金华市| 正定县| 麻栗坡县| 胶南市| 子长县| 安吉县| 扎囊县| 天镇县| 湘潭县| 离岛区| 乌鲁木齐市| 丁青县| 甘孜| 信丰县| 苍梧县| 靖边县| 娱乐| 丰城市| 肇源县| 阜平县| 诸暨市| 清苑县| 淳化县| 嘉义县| 宜州市| 诸城市| 南陵县| 定远县| 开原市| 孟连| 利川市| 河南省| 若尔盖县| 定边县| 鹤峰县| 克拉玛依市| 澄迈县| 漠河县|