Directives & Data Rendering
Repo lives at:
https://github.com/sdras/intro-to-vue
(Other links in Readme)
Hello World!
<div id="app">{{ message }} Nice to meet Vue.</div>
Vanilla JS vs Vue for Conditional Rendering
const items = [
'thingie',
'another thingie',
'lots of stuff',
'yadda yadda'
];
function listOfStuff() {
const full_list = items.map(el => `<li> ${el} </li>`).join('');
const contain = document.querySelector('#container');
contain.innerHTML = `<ul> ${full_list} </ul>`;
}
listOfStuff();
HTML:
<div id="container"></div>
Yields:
const App = {
data() {
return {
items: [
'thingie',
'another thingie',
'lots of stuff',
'yadda yadda'
]
}
}
}
HTML:
<div id="app">
<ul>
<li v-for="item in items">
{{ item }}
</li>
</ul>
</div>
Yields:
Creates a relationship between the data in the instance/component and a form input, so you can dynamically update values
Accepting user input and managing it in a responsible manner
const App = {
data() {
return {
message: 'This is a good place to type things.'
}
}
}
<div id="app">
<h3>Type here:</h3>
<textarea v-model="message" class="message" rows="5" maxlength="72"/>
<br>
<p class="booktext">{{ message }} </p>
</div>
Is a conditional that will display information depending on meeting a requirement. This can be anything- buttons, forms, divs, components.
Pretty straightforward- you can conditionally render one thing or another. There's also v-else-if
Must be siblings.
or
One of the most useful directives so there's a shortcut! We can use it for so many things- class and style binding, creating dynamic props, etc...
Interactive style bindings
<div id="contain" :style="{ perspectiveOrigin: `${x}% ${y}%` }">
This pen.
Loops through a set of values
(previous example- item in items)
Can also do a static number
Needs to be unique, it's what Vue uses to track VDOM changes
<li v-for="num in 5" :key="num">
and
Not quite as useful, v-once will not update once it's been rendered.
v-pre will print out the inner text exactly how it is, including code (good for documentation)
or
Extremely useful so there's a shortcut! v-on is great for binding to events like click and mouseenter. You're able to pass in a parameter for the event like (e)
We can also use ternaries directly
<div v-on="
mousedown: doThis,
mouseup: doThat
">
</div>
<div @="
mousedown: doThis,
mouseup: doThat
">
</div>
Great for strings that have html elements that need to be rendered!
Warnings:
Not the same as templates: inserted as plain HTML
Don't use on user-rendered content, avoid XSS attacks
Similar to using mustache templates
Warning:
If you want to dynamically update, it's recommended to use mustache templates instead