In this module we are going to explore Vue’s core concepts. This is relatively a big section of the course as we learn about the fundamentals of working with vue.
- Vue can be used to define the goal instead of the steps (-> declarative approach)
- Connect Vue to HTML via “mount”: Vue then renders the real DOM based on the connected template.
- Data can be output in that template. You can Bind data via interpolation (**) or the v-bind (“:”) directive. You listen for events via v-on(“@”)
In order to make these features more uselful, we rely on vue’s reactivity
Vue updates the real DOM for you when bound data changes. Computed Properties and watchers allow you to react to data changes.
Vue can help in styling with achieving dynamic styling.
Dynamic CSS classes and inline style bindings are supported by vue. Vue offers multiple special syntaxes (object, array-based) for efficient bindings.
v-once
div
element highlighted when clicked upon
Project Files for this Lecture
.
└── 2.1 Basics 01 Starting Code/
├── app.js
├── index.html
└── styles.css
The objective is to output the desired course goal inside of the paragraph tag using vue which could potentially be changed dynamically.
First step would be to create a vue app. But now we can store it inside of a constant like so-
const app = Vue.createApp();
And now we have to let vue know which part of the HTML section should be controlled by it. Since the section user-goal
will be manipulated, we will use the mount
#Methods on the app
object.
mount
method required a string which holds a CSS Selector which uniquely identifies the element in our DOM.
app.mount("#user-goal");
We can now use Vue features to manipulate this section by passing an object to create app. This can be used to configure the various options of this app.
One option that we can set is the data
option and it requires a function as a value. This data function returns an #object.
data() {
return {
};
}
In this returned object we can now set up any key value pairs with any key of your choice. Anything that’s part of the returned object can now be used in the vue controlled HTML part.
To output data, vue will scan the HTML code and detect a certain #Syntax which it supports. The syntax used for this is ``.
Between those braces, you can reference your returned data object properties. This syntax is called #interpolation. It means that in this braces you can reference properties of the returned object.
If you use #interpolation outside the mounted portion, it will not work.
If you want to pass a dynamic value to an attribute, such as the href
attribute, we need to use the vue-bind
syntax.
For that we use a vue Directive which is a simple instruction we add in the HTML code. We can use such directives on HTML elements.
The directive here is v-bind
which is a reserved name detected and understood by Vue. It tells vue to set the value of sometihng. We add a colon after v-bind
and then the attribute’s name. For anchor tag and href it will be-
<a v-bind:href="">Some Text</a>
This directive is the attrubution alternative to #interpolation #Syntax.
Another option similiar to data
for our vue app would be the methods
option. It allows us to define functions which should execute when they are called or when a user event such as a button click occurs.
We pass a javascript #object in methods instead of a function as seen in data
. methods
takes an object which would be full of functions. And these functions can be defined as regular javascript functions.
methods: {
function1 () {
}
}
In this lecture we are goin to learn about how to access the data stored inside of the data
key from the methods
key. In order to do this we have to use a special #Syntax like so-
const app = Vue.createApp({
data() {
return {
x_variable: 'Some data stored here'
}
};
},
methods: {
getData() {
hello = this.x_variable
}
})
Here, if we try to use x_variable
, it would not work as it is not defined in that #namespace. If we want to use it, we would have to get it by using this
which would refer to the variable defined in the data
key. All of this is managed by Vue.
To output HTML structure we use the v-html
#directive which tells vue that the content should be interpreted as HTML code and not just text.
Here you can find the project files for this module.
.
└── 2.10 Understand Event Binding/
├── app.js
├── index.html
└── styles.css
We would now learn how to react to user input/ events, making pages dynamic. In project’s index.html file there is a section with a different ID as well as 2 buttons- add or remove. We also have a paragraph where a counter is outputted (managed in the vue app.)
When the add
button is clicked, a value of 1 is added to the counter. When the reduced
button is clicked, 1 is removed from the counter.
In order to do this we can use the v-bind
directive which is helpful for setting up the value of an attribute, but we can also use the v-on
directive for event listeners as we want to react to a certain event. In this case our event is a click.
<button v-on:click="counter++"> Add </button>
Other events you can listen include but are not limited to:
It is a bad practice to put login in your HTML code. Logic should go into the js code. So we would require a function. So we would require a methods key.
methods: {
add() {
this.counter++;
}
}
This method can be directly called in the vue controlled app like so:
<button v-on:click="add()">Add</button>
Method arguments work in the same way as normal vanilla javascript event arguments.
methods: {
add(num) {
this.counter = this.counter + num;
}
}
<button v-on:click="add(7)">Add</button>
Another directive that we should know about is v-on:input=""
. And this only available on input elements. With this we can execute some vue code whenever there is some input (for ever keystroke).
Note
The order of methods does not matter similar to the order of methods.
Here is an example showcasing how the input directive works
As the name suggests event modifiers basically modify the events. Let’s take the example of a form.
<form>
<input type="text" />
<button>Submit</button>
</form>
The problem here is that once the button is clicked, the entire page will reload which is a default set by the browser. The browser sends an HTTP request to the server and then reloads, however here we have no such server.
If you want to prevent this browser default, and handle it manually, there are two ways of doing that.
v-on:sumbit
We can do this with the submit event with the v-on
directive which points to a method which can look something like-
methods: {
submitForm(event) {
event.preventDefault(); //Prevents relaoding the page (Vanilla JS)
alert('submitted')
},
}
.prevent
modifiersThere are certain built-in modifiers which can be connected to events to change the behaviour of that event. You can add modifiers with a .
like so:
<form v-on:submit.prevent="submitForm"></form>
click.right/left
- Specify whether the user is right/left clicking
Here we looked at how with v-on:input
runs the mothod with ever keystroke, but if we need to run a method once, that is when we press enter then we should instead use the v-on:keyup
event along with the .key
modifier like so-
<input v-on:keyup.enter="mymethod" />
You can also listen to ctrl
or shift
, etx. All keybaord keys are possible here.
v-once
This is rarely needed but can be useful. If you have some data that changes and you want to preserver its initial state and not reflect any other changes, you can use the v-once
directive.
<p v-once></p>
v-model
directive takes the variable you want it to manage. That variable is then managed by vue such that its updated on the input event. And the variable’s value is then sent back to that input. This is called two-way binding.
Using methods inside of vue tags is not ideal as whenever something updates, vue would have to re-run the code which is not good in terms of performance.
Computed properties are like methods, but vue will be aware of their dependencies and only re-execute them if one of the dependencies change.
Computed is the third configuration option of the vue app which also include methods
and data
. Position does not matter. Computed takes an object as a value and in that value you can define a couple of methods. Do note that what you are going to define in computed
are actually going to be treated like properties and not exactly mothods.
computed: {
fullname() {
if (this.name === "") {
return "";
}
return this.name + " Surname";
},
},
This is an example of a computed property. Vue will be aware of its dependencies and execute it whenever its dependency is updated.
<p> </p>
NOTE: Do note that I am using fullname
instead of fullname()
because like I have mentioned earlier we have to treat these computed properties as data properties. And this is why we should also name our computed properties similar to data properties.
Watchers are function which you can tell vue to execute when its dependencies change. It is similar to computed properties and you can use watchers instead of that.
Similar to computed properties, we define a bunch of methods inside an object which watcher
takes in as a value.
watch: {
name(newValue, oldValue) {
this.fullname = oldvalue + ' ' + ' something';
}
}
Watchers are best suited for scenarios like timers, or for sending HTTP requests.
Methods | Computed | Watch </tr> |
---|---|---|
Use with event binding OR data binding | Use with only data binding. | Not used directly in template </tr> |
Data Binding: Method is executed for every "re-render" cycle of the component. | Computed properties are only re-evaluated if one of their "used values" changed. | Allows you to run any code in reaction to some changed data (e.g. send Http request) </tr> |
Use for events or data that really needs to be re-evaluated all the time. | Use for data that depends on other data | Use for any non-data update you want to make </tr> </table> # Shorthands Directives like `v-on` and `v-bind` are so often used, that there are shorthands for them. For example, `v-on:click` can be replaced by `@click` and for `v-bind` directive you can just use a semicolon like `v-bind=value` can be written as `:value`. # Dynamic Styling In vue, it is possible to change the style of elements dynamically on reaction to some event. #### **Example 1: Div selected: Make a `div` element highlighted when clicked upon** One way to do this would be to set 3 bool vars and then change their values when the user clicks on them. ```html <div class="demo" @click="boxSelected('a')"></div> <div class="demo" @click="boxSelected('b')"></div> <div class="demo" @click="boxSelected('c')"></div> ``` ```js data() { return { aselected = false, bselected = false, cselected = false, } }, methods: { boxSelected(box) { if (box === 'a') { this.aselected = true this.bselected = false this.cselected = false } else if (box === 'b') { this.aselected = false this.bselected = true this.cselected = false } else if (box === 'c') { this.aselected = false this.bselected = false this.cselected = true } } } ``` So in order to make a box look like its highlighted, we can change its border colour to red. We can bind style to some value using `v-bind` ```html <div :style="{borderColor: aselected ? 'red' : '#ccc'}"> ``` ## Adding CSS classes dynamically Let's say we have a speical css class- ```css .active { border-color : red; background-color : salmon; } ``` and we want to apply it to a particular element when it is clicked upon, so in order to this, we can bind the class attribute dynamically- ```html <div :class="aselected ? 'demo active' : 'demo'" @click="" ></div> ``` or it can be re-written as ```html <div class="demo" :class="aselected ? 'demo active' : 'demo'" @click="" ></div> ``` |