There are some tricks which can’t be found easily in Vue.js homepage. So, for convenient, I summarized them here.
Vue
Access Global Variable in Template
Have you ever done something like this in lots of components?
<template> |
or
<template> |
Actually, you don’t have to, you can register window
or bus
in Vue.prototype
like:
Vue.prototype.window = window; |
in the main.js or the entry file. Then you can use bus
or window
in template
directly. Also, this usage prevents Vue watching the attributes of bus
or window
which would bring a waste of performance.
Reactive or Not Reactive
Always, if we want a data reactive, we have to do something like this:
data: { |
Set some initial value to adds all the properties found in its data object to Vue’s reactivity system.
Things we need to take care about is:
- If we want to add reactive attributes dynamically, we have to use something like
Vue.set
orthis.$set
. Otherwise, they might not be reactive. - If we definitely don’t want some data to participate in Vue’s reactivity system even we initialize it in
data
. We can use something likeObject.freeze()
. For example, freeze a huge array to improve performance.
Scoped Style Won’t Work on Dynamically Inserted Elements
I always use the <style scoped>
tag in .vue files. It is always good except when we want to insert elements dynamically. For example:
<template> |
color: red
won’t work on .App__title
because of scoped
. The actual style is rendered with a unique attribute like:
So, how do we solve this? /deep/
or >>>
.
<style scoped> |
They can be used to override child component style. Here is the doc.
Smarter Watchers
Have you ever written code like this:
{ |
Actually, you can simplify it by
{ |
As the doc said:
Passing in immediate: true in the option will trigger the callback immediately with the current value of the expression.
$attrs and $listeners
I don’t know if you have used $attrs
and $listeners
from this
. However, I never used those until I met this situation. For example:
<div id="app"> |
It’s obviously tedious to bind every attribute and listener by hand. Actually, this is where $attrs
and $listeners
will help us. We can write the BaseInput
template
like:
let BaseInput = { |
Vue-Router
$router and $route
Have you ever wonder about the relationship between $router
and $route
? I give you a hint:
this.$router.currentRoute === this.$route; //true |
Vuex
Commit Data by One Mutation
We can’t directly mutate state
in Vuex. Instead, we have to commit
a mutation
to mutate the data. However, it would be tedious to write lots of similar mutations like this:
let store = new Vuex.Store({ |
We can write a public mutation to do this like:
let store = new Vuex.Store({ |
Then we can mutate state
in anywhere with only one mutation like:
commit( |
It would also work for modules!