Vue Flashcards
dynamically toggle classes
v-bind We can pass an object to v-bind:class to dynamically toggle classes:
<div></div>
This is a very commonly used feature in Vue. Because it’s so common, there’s a shorthand for v-bind, and it’s just a colon :
The above syntax means the presence of the active class will be determined by the truthiness of the data property isActive.
You can have multiple classes toggled by having more fields in the object. In addition, the v-bind:class directive can also co-exist with the plain class attribute. So given the following template:
<div></div>
The bound object doesn’t have to be inline:
<div></div>
data: { classObject: { active: true, 'text-danger': false } }
STYLE:
<div></div>
data: { styleObject: { color: 'red', fontSize: '13px' } }
conditionally render a block.
v-if and v-else directives
v-else-if
v-show
The directive v-if is used to conditionally render a block. The block will only be rendered if the directive’s expression returns a truthy value.
<h1>Vue is awesome!</h1>
It is also possible to add an “else block” with v-else:
<h1>Vue is awesome!</h1>
<h1>Oh no 😢</h1>
v-show
It will conditionally add or remove the CSS property display: none to the element.
v-for directive
We use an alias for the element in the array being iterated on, and specify the name of the array we are looping through. Ex: v-for=”item in items”
listen for DOM events that we can use to trigger methods.
v-on
shorthand @
Listening to Events
We can use the v-on directive to listen to DOM events and run some JavaScript when they’re triggered.
For example:
<div>
Add 1
<p>The button above has been clicked {{ counter }} times.</p>
</div>
The logic for many event handlers will be more complex though, so keeping your JavaScript in the value of the v-on attribute isn’t feasible. That’s why v-on can also accept the name of a method you’d like to call.
<div>
Greet
</div>
var example2 = new Vue({ el: '#example-2', data: { name: 'Vue.js' }, // define methods under the `methods` object methods: { greet: function (event) { // `this` inside methods points to the Vue instance alert('Hello ' + this.name + '!') // `event` is the native DOM event if (event) { alert(event.target.tagName) } } } })
// you can invoke methods in JavaScript too example2.greet() // => 'Hello Vue.js!'
Computed Properties
computed properties calculate a value rather than store a value
add the computed option to our instance
<div>
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({ el: '#example', data: { message: 'Hello' }, computed: { // a computed getter reversedMessage: function () { // `this` points to the vm instance return this.message.split('').reverse().join('') } } })
Here we have declared a computed property reversedMessage. The function we provided will be used as the getter function for the property vm.reversedMessage
component
reusable Vue instances
Vue.component('name', { props: {}, template: ` <div class="product"> </div> `, data() { return { } }, methods: { }, computed: { } } })
communicating event up to the parent
this.$emit(‘name-of-event’, id)
<div></div>
two-way binding
forms
v-model=”name”
v-model.number=”rating” - cast as number
@submit.prevent=”onSubmit” - prevent default behaviour
<p> Name: </p> <p> Review: </p> <p> Rating:
5 4 3 2 1
</p> <p> </p>
data() { return { name: null, review: null, rating: null } }
onSubmit() { let productReview = { name: this.name, review: this.review, rating: this.rating } this.$emit('review-submitted', productReview) this.name = null this.review = null this.rating = null }
Now we need to listen for that announcement on product-review.
Now we need to listen for that announcement on product-review.
Form Validation
Fortunately, HTML5 provides you with the required attribute, like so:
Custom Form Validation
In our product-review component’s data we’ll add an array for errors:
data() { return { name: null, review: null, rating: null, errors: [] } }
We want to add an error into that array whenever one of our fields is empty. So we can say:
if(!this.name) this.errors.push("Name required.") if(!this.review) this.errors.push("Review required.") if(!this.rating) this.errors.push("Rating required.")
<p> <b>Please correct the following error(s):</b> </p><ul> <li>{{ error }}</li> </ul>
Using .number
Using the .number modifier on v-model is a helpful feature, but please be aware there is a known bug with it. If the value is blank, it will turn back into a string. The Vue.js Cookbook offers the solution to wrap that data in the Number method, like so:
Number(this.myNumber)
global event bus
A common solution for communicating from a grandchild up to a grandparent, or for communicating between components
var eventBus = new Vue()
In our product-review component, instead of saying:
this.$emit('review-submitted', productReview)
We’ll instead use the eventBus to emit the event, along with its payload: productReview.
eventBus.$emit('review-submitted', productReview)
Now, we no longer need to listen for the review-submitted event on our product-review component, so we’ll remove that.
we’ll listen for that event using this code:
eventBus.$on('review-submitted', productReview => { this.reviews.push(productReview) })
Using an event bus is a common solution and you may see it in others’ Vue code, but please be aware this isn’t the best solution for communicating amongst components within your app.
As your app grows, you’ll want to implement Vue’s own state management solution: Vuex. This is a state-management pattern and library. You’ll also learn all about Vuex in our Mastering Vuex course, where we’ll teach you how to build a production-level apps that can scale, from setting up your project using the Vue CLI all the way to deployment.
mounted
What’s mounted? That’s a lifecycle hook, which is a function that is called once the component has mounted to the DOM. Now, once product has mounted, it will be listening for the review-submitted event. And once it hears it, it’ll add the new productReview to its data.