将来を見据えたウェブ・アプリケーションの構築:The Codestのエキスパート・チームによる洞察
The Codestが、最先端技術を駆使してスケーラブルでインタラクティブなウェブアプリケーションを作成し、あらゆるプラットフォームでシームレスなユーザー体験を提供することにどのように秀でているかをご覧ください。The Codestの専門知識がどのようにデジタルトランスフォーメーションとビジネス...
Vue is a rapidly growing progressive framework for building user interfaces. It became the JavaScript framework with the most stars on GitHub and the most highly starred project of 2016 and 2017 on in the same portal.
Creating applications in Vue is really simple as such, but if you want to build good quality applications, you’re up for a bit more of a challenge.
Being a part of The Codest チーム and real advocate of Vue technology, I want to share some tips (not copied from official Vue docs) which will effortlessly improve コード quality and the performance of Vue applications.
I don’t want to repeat what has already been said. There’s a style guide in Vue docs:
Vue 2 docs – style guide または
Vue 3 docs – style guide
You can find there four Rule categories. We really care about three of them:
Essential
rules preventing us from errors,Recommended
そして strongly recommended
rules for keeping best practices – to improve quality and readability of code.You may think… “What?! Do I have to remember every rule?” Of course you don’t. You can use ESLint to take care of those rules for you. You just have to set everything properly in the ESLint configuration file. I suggest using the recommended
preset as you get a totally free set of rules that help you in building apps with good practices. How to set it up?
By default, you should find 拡張
key in ESLint config and replace "plugin:vue/essential"
と "plugin:vue/recommended"
, that’s all.
Of course, there’s a few rules you should remember, because ESLint cannot handle everything on its own. For example:
$_namespace_
private properties in plugins, mixins, etc.,It may sometimes be necessary to render conditionally more than 1 element, but people often write something like that:
content
content
content
It’s unnecessary because we can write it more elegantly:
<code> <template v-if="condition">
<div>内容</div>
<div>内容</div>
<div>内容</div>
</template>
But what if we want to do it as a root element? In Vue, we can’t use <template>
for this purpose. In some cases, wrapping in div could be enough.
That’s ok, but, as much as we may want, sometimes we can’t wrap elements in div, for example, because of html semantic (e.g. <li>
has to be a direct child of <ul>
または <ol>
). So when we have to write:
<li
v-for="item in items"
:key="item.id"
>
(( item.name ))
</li>
…and we’ll see an error like that :
We can deal with it by using JSX and a functional component, also we should pass a boolean and it will replace the v-if.
</>
Actually, this is only one of the examples of what you shouldn’t do in components. Simply do what is locally necessary in components logic. Every method that could be external should be separated and only called in components e.g. business logic.
例
Instead of a method like this:
created() (
this.fetchArticles();
),
methods: (
async fetchArticles() (
try (
const data = await axios.get(url);
this.articles = data.articles;
) catch (e) (
// handle error
)
)
)
Write something like this – just call the proper method that will return API results:
async fetchArticles() (
try (
this.articles = await ArticlesService.fetchAll();
) catch (e) (
// handle error
)
)
Sometimes using props is just enough, but there are also cases when they are not efficient. It may happen in situations where we would have to add too many props to make the component work like we want it to. The simplest example could be a button component. Without any doubt, it’s a component which could be used anywhere in an application. So, let’s consider a button component like this one.
(( text ))
</>
At this stage, it’s a simple component which accepts only text prop. Ok, but it may not be enough as we will need icons in the button. In this case, we have to add another 2 props (2, because we want to have the option to add before or after text). So, the component will look like this:
(( text ))
</>
It’s not bad, we have only 3 props, but…
What if we need a loading indicator? Well, we would have to add another prop. And that’s for every new feature! Does keeping up with the growth of the number of components sound challenging now? Yes, it does, definitely!
Simpler, right? Ok, but how can we get the add icon feature? It’s really easy! Just use the component like this:
Back
Next
I will share with you some tips that are really easy to implement, so you can instantly benefit.
Sometimes we would have routes are available only for admins, or user with particular access, they may also be visited less than others. They are perfect cases for using the lazy load route.
Just use the arrow function in your component property to return import function:
export default new VueRouter (
(
mode: 'history',
routes: [
(
path: '/landing',
component: () => import('../pages/p-welcome'),
name: 'welcome'
),
…
Instead of:
import PWelcome from '@/pages/p-welcome';
export default new VueRouter (
(
mode: 'history',
routes: [
(
path: '/landing',
component: PWelcome, //just imported component
name: 'welcome'
),
A similar situation may happen with Vue components. We can lazily import single file components like this:
const lazyComponent = () => import('pathToComponent.vue')
export default (
components: (lazyComponent )
)
// Another syntax
export default (
components: (
lazyComponent: () => import('pathToComponent.vue')
)
)
Thanks to the lazy load of that component, it will be downloaded only when requested. For example, if we have a component with v-if, it will be requested only if the component is to render. So unless the v-if value is true, the component will not be loaded. That’s why lazy importing can be also used for JavaScript files.
Bonus: When using Vue CLI 3+, every lazily loaded resource is prefetched by default!
Consider a component like this one:
<template>
<input
:value="value"
class="base-input"
@input="$emit('input', $event.target.value)"
>
</template>
Without any problems, we can use it like this:
または
It works, because Vue allows you to pass html attributes to the component, even if you didn’t declare them as props. The html attributes are applied to the component’s root element (input, in this case).
The problem appears when we want to expand our input component, since it could look like this:
<code> <template>
<div class="form-group">
<label :for="id">(( label ))</label>
<input
:id="id"
:value="value"
class="base-input"
@input="$emit('input', $event.target.value)"
>
</div>
</template>
Now, using the component this way:
<base-input
v-model="text"
type="text"
placeholder="Write something"
/>
will not work like we want, because the type and the placeholder will be applied to div (root element) and that’s make no sense. So, we need to deal with it, because we want to add our attributes to the input element. Your first thought may be “let’s add the props we need!” and of course that will work, but… what if we want to use type
, autocomplete
, placeholder
, autofocus
, disabled
, inputmode
, etc., then we have to define the props for every html attribute. I personally don’t like this lengthy method, so let’s look for something better!
We can deal with the whole problem in just two lines.
<template>
<div class="form-group">
<label :for="id">(( label ))</label>
<!-- pay attention to v-bind="$attrs" -->
<input
:id="id"
v-bind="$attrs"
:value="value"
class="base-input"
@input="$emit('input', $event.target.value)"
>
</div>
</template>
<script>
export default (
name: 'BaseInput',
inheritAttrs: false, // <- pay attention to this line
props: ['value', 'label', 'id']
);
</script>
を使うことができる。 v-bind="$attrs"
and pass attributes directly to <input>
without declaring huge amounts of props. Also, remember about adding the option inheritAttrs: false
to disable passing the attributes to the root element. Let’s go a bit further: what if we need to add event listeners to this input? Again, it could be handled by props or custom events, but there’s a better solution.
<template>
<div class="form-group">
<label :for="id">(( label ))</label>
<!-- pay attention to v-on="listeners" -->
<input
:id="id"
v-bind="$attrs"
:value="value"
class="base-input"
v-on="listeners"
>
</div>
</template>
<script>
export default (
name: 'BaseInput',
inheritAttrs: false,
props: ['value', 'label', 'id'],
computed: (
listeners() (
return (
...this.$listeners,
input: event => this.$emit('input', event.target.value)
);
)
)
);
</script>
There’s a new computed property that returns the component for listeners and adds the input listener. We use that computed input by simply writing v-on="listeners"
.
We often fetch some data on a created (or mounted) hook, but then we need fetch that data with every change of a property, e.g., current page of pagination. Some tend to write it down like this:
<script>
export default (
name: 'SomeComponent',
watch: (
someWatchedProperty() (
this.fetchData();
)
),
created() (
this.fetchData();
),
methods: (
fetchData() (
// handle fetch data
)
)
);
</script>
Of course, it works, but… It’s not the best approach, not even a good one. So, let’s check how we can refactor this, An example of not so bad approach:
<script>
export default (
name: 'SomeComponent',
watch: (
someWatchedProperty: 'fetchData'
),
created() (
this.fetchData();
),
methods: (
fetchData() (
// handle fetch data
)
)
);
</script>
The above version is better because another method is not necessary, we only named a method that should be called on to change watchedProperty.
An even better approach:
<script>
export default (
name: 'SomeComponent',
watch: (
someWatchedProperty: (
handler: 'fetchData',
immediate: true
)
),
methods: (
fetchData() (
// handle fetch data
)
)
);
</script>
We got rid of the created hook. By adding the option ‘immediate,’ we make that component call on the fetchData method immediately after the start of the observation (it’s a bit before the created hook and after beforeCreated), so it can be used instead of the created hook.
These tips will not make your application perfect but using them will quickly improve the quality of your code. Also, I hope you will find something of interest in the above examples.
Note that some of them were simplified for the article’s purposes.
続きを読む