Notice that you are building a new instance of Vue:
new Vue({
el: '#app',
data: {
myClass: '',
}
});
Note that the variable myClass
is started as an empty string. Now note in your template the following:
<input type="text" v-on:input="myClass = $event.target.value">
The directive v-on
is used to link an event to the element in question. In this case, with v-on:input
, Vue will listen for events input
and, when issued, shall carry out the instruction indicated.
In this case, whenever the event input
is issued by the user, you have instructed Vue to execute this code: myClass = $event.target.value
, which it basically assigns to the variable myClass
(defined in the creation of the component) the value entered by the user.
Now, going to this part:
<p v-bind:class="myClass"> ... </p>
The directive v-bind
is used to assign the value of some variable to some HTML attribute, dynamically. Thus, with v-bind:class
, you will always change the class of the element <p>
in response to the event input
user (which changes the variable myClass
.
In his example, Vue has no notion of the background color of the element. He only "knows" the class being applied. The only part of your application that really "knows" the background color is CSS.
Note that you define, in your style sheet, two classes with two respective background colors. Whenever Vue.js (in response to the event input
user) assigns one of the two classes defined in the element, the CSS will automatically apply the defined styles.
Generally speaking, CSS is "reactive" automatically. Whenever a class is changed or removed (by Javascript, for example), the browser already understands that need to redo styling, so that the CSS is applied automatically, without the need for interventions frameworks or libraries.
When typing in input, it makes the connection
myClass = $event.target.value
, transferring the valuepurple
for example for the variablemyClass
. Below, he uses thev-bind:class
to assign a class to thep
, in that case the classpurple
(myclass value), which is defined in the CSS.– ThRnk
Try it this way:
<input type="text" v-model="myClass">
– adventistaam