Home / Snippets / Vue Js Methods to computed properties
Vue Js Methods to computed properties cover

Vue Js Methods to computed properties

234

3 years ago

0 comments

When you find yourself in a need of using an argument for a computed property, consider creating and moving the logic into a child component.

By doing this approach the components will provide the decoupling which makes it more structured, modular, and computed property caching.

Before

<template>
  <section class="posts">
    <article v-for="post in posts">
      <a :href="getUrl(post)">{{ getTitle(post) }}</a>
    </article>
  </section>
</template>

<script>
export default {
  methods: {
    getUrl (post) { ... },
    getTitle (post) { ... }
  }
}

After

<!-- 1. PostList.vue -->
<template>
  <section class="posts">
    <PostItem v-for="post in posts" :post="post"/>
  </section>
</template>

<!-- 2. PostItem.vue -->
<template>
  <article v-for="post in posts">
    <a :href="url">{{ title }}</a>
  </article>
</template>

<script>
export default {
  props: ['post'],
  computed: {
    url () { /* compute on this.post */ },
    title () { /* compute on this.post */ }
  }
}
</script>
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this