Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Displaying, Looping, Searching, and Filtering Data Chapter 2

You should try and avoid adding HTML to your Vue instance, as it starts to mix up the


View in the ViewModel and Model of our MVVM structure. There is also the danger you
output an invalid HTML tag inside another. You should only use v-html with data you


trust, because using it with an external API could be a security concern as it would allow
the API to have control over your application. A potentially malicious API could use v-


html to inject undesired content and HTML. Only use v-html with data you can fully


trust.


Declarative rendering


Regular HTML attributes, such as the src of the tag, can be dynamically populated


with Vue using the v-bind: attribute. This allows you to populate any existing attribute


with data from your Vue application. This might be an image source or element ID.


The bind option gets used by prepending the attribute you wish to populate. For example,


if you wished to populate an image source with the value of a data key called


imageSource, you would do the following:


View:


Create an img tag in your view app space, with a dynamic src attribute, using v-bind and


a variable called imageSource.


<div id="app">
<img v-bind:src="imageSource">
</div>

JavaScript:


Create a variable in your Vue JavaScript code called imageSource. Add the URL to the


desired image:


const app = new Vue({
el: '#app',

data: {
imageSource: 'http://via.placeholder.com/350x150'
}
});

The v-bind: attribute can be shortened to just :, so, for example, v-bind:src would


become :src.

Free download pdf