The vuejs model directive

This will be a quick post on the vuejs model directive that might need to be used now and then when doing something with input elements in a template. The model directive may not need to always be used when working out an interface in a template but I have found that I need to use it with input, select, and text area tags. The vue model directive will make it so that you have two way bindings between input tags, and a value in the data object of a vue instance. So that when something changes in the data object, that change will effect the value of an input tag, and that if the user changes the value in the input tag that will change the value in the data object.

1 - vue model basic example

So lets start out with just a very simple example of the vue model directive that will help to show that the deal is with this one. Here I have a Vue instance a script tag that will mount to a hard coded html element my way of the vue el option. When it mounts the mount lief cycle hook will fire and call an add method that will add the value of the a, and b properties in the data object to get the value of c. This add method will also always fire when there is a change to the data object because of the updated hook. In my template I am making it so that there is a two way binding between input tags in the template, and corresponding values in the data object that I want to change when the user updates the value of the input tags.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<html>
<head>
<title>vue model</title>
<script src="/js/vuejs/2.6.10/vue.js"></script>
</head>
<body>
<div id="app"></div>
<script>
new Vue({
el: '#app',
template: '<div><input type="text" v-model="a"> + ' +
'<input type="text" v-model="b" > = <span v-text="c" ></span></div>',
data: {
a: 1,
b: 3,
c: 0
},
mounted: function () {
this.add();
},
updated: function () {
this.add();
},
methods: {
add: function () {
this.c = parseInt(this.a) + parseInt(this.b);
}
}
});
</script>
</body>
</html>

2 - Conclusion

So the Vue module directive is what needs to be used to make a two way binding between the value property of various HTML elements that are used to get user input, and the data object of a vue.js instance. I use it all the time in any template that requires the use of it.