Declarative code and importance in Vue

Declarative code and importance in Vue

Declarative code and importance in Vue - the most important feature in Vue

What is declarative code?

The most common way of programming a computer is to give it a list of instructions. The computer will then go through each instruction step-by-step until the program finishes.

This is called imperative programming.

It's like you're explaining your favourite pasta recipe to someone who has never cooked in their life.

You can't just tell them the ingredients for the sauce and expect them to produce something delicious. They need to know every single step in the most detail possible:

  • Slice the mushrooms

    • Hold the knife like this
    • Slice them this thick
  • Boil the pasta

    • Put in this much water
    • Add a bit of salt
    • Do this to make sure the pot doesn't boil over

If you leave any detail out, they'll probably make a mistake and ruin the dish

But what if you were explaining this recipe to someone who has experience cooking?

Your instructions would look like this instead:

  • Slice the mushrooms
  • Boil the pasta
  • Heat up some butter and cream in a sauce pan
  • Mix in garlic, parmesan, cream cheese, salt and pepper

You don't need to specify how to do each of those things, because the chef knows that. All you need to do is to tell them what they are making.

This is called declarative programming.

Instead of specifying every single step of the program, you only need to tell the computer what should happen, and it knows how to handle the rest.

Computed props allow you to write declarative code

We have a component here that takes in a list prop, but always renders just the top 3 items:

export default {
  props: {
    list: {
      type: Array,
    },
  },

  data() {
    return {
      topThree: [],
    };
  },

  watch: {
    list: {
      // Run as soon as the component loads
      immediate: true,
      handler() {
        // Recalculate and set the `topThree` variable
        this.topThree = this.getTopThree(this.list);
      },
    },
  },

  methods: {
    getTopThree(list) {
      // Sort the array
      list.sort();

      // Return first 3 items
      return list.slice(2);
    }
  }
}

Our component state topThree will always contain the top three items in the list, no matter how the list prop changes.

Step-by-step, this is what it's doing: 1. If the list prop changes, our watcher fires 1. We pass this.list to our getTopThree method to calculate the top 3 items 1. We take those items and update our component state

We're following an imperative approach here, by specifying exactly what needs to happen.

Actually, our watcher is somewhat declarative, because we don't need to write any logic to check when props update. Vue just runs the function for us when the list prop changes.

But if we switch to using a computed prop, we end up with a more declarative approach. You'll also see that it's a simpler and more understandable way of writing this functionality.

Declarative code is better code

To switch this to a computed prop we'll first get rid of the watcher completely:

export default {
  props: {
    list: {
      type: Array,
    },
  },

  data() {
    return {
      topThree: [],
    };
  },

  methods: {
    getTopThree(list) {
      // Sort the array
      list.sort();

      // Return first 3 items
      return list.slice(2);
    }
  }
}

We can also get rid of our data section as well:

export default {
  props: {
    list: {
      type: Array,
    },
  },

  methods: {
    getTopThree(list) {
      // Sort the array
      list.sort();

      // Return first 3 items
      return list.slice(2);
    }
  }
}

Now we can convert the method into a computed prop that we'll call topThree:

export default {
  props: {
    list: {
      type: Array,
    },
  },

  computed: {
    topThree(list) {
      // Sort the array
      list.sort();

      // Return first 3 items
      return list.slice(2);
    }
  }
}

However, computed props can't accept any arguments. Instead we'll just grab the list prop directly from inside the computed prop:

export default {
  props: {
    list: {
      type: Array,
    },
  },

  computed: {
    topThree() {
      // Copy the list to avoid side effects
      const copy = this.list.slice();

      // Sort the array
      copy.sort();

      // Return first 3 items
      return copy.slice(2);
    }
  }
}

As we saw in Lesson 2.2 — Mutating an Array, we have to make a copy of this list first so we don't accidentally modify it and produce a confusing side effect.

Here are some of the benefits that we can already see just from looking at this small illustration:

  • Less code — Our component here went from 33 lines to 19, a significant reduction
  • Much simpler — Instead of four different pieces in our component (props, data, watcher, and methods) we just have two to think about (props and computed)
  • Focused on our goals — We're not wasting our time with writing code to trigger the update, which has nothing to do with the feature that we're trying to write. This is especially important when someone is trying to read the code and understand what it's doing.

I think you'd probably agree with me that the approach with computed props is easier to understand as well.

Summary

In this lesson we explored what declarative code is, and saw that one of the reasons why people love Vue so much is because it allows us to write our code more declaratively.

We also saw that computed props are the main way that we can convert our imperative code to be more declarative, and saw that there are several benefits to writing code this way.

Because of this, computed props are the most important feature in Vue in my opinion — hopefully I've convinced you.

Thank you for reading!

Hire React Js Developer from Expert React JS Development Company

Hire React Js Developer from Expert React JS Development Company

Are you looking to [hire React JS developer](https://www.mobiwebtech.com/react-js-development-company/ "hire React JS developer") from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team...

Are you looking to hire React JS developer from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team of expert React JS developers, you can hire them on an hourly, weekly or monthly basis for the successful completion of your dream project.

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.

10 Best Vue Icon Component For Your Vue.js App

10 Best Vue Icon Component For Your Vue.js App

In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

Icons are the vital element of the user interface of the product enabling successful and effective interaction with it. In this article, I will collect 10 Vue icon component to bring more interactivity, better UI design to your Vue application.

1. Animated SweetAlert Icons for Vue

A clean and simple Vue wrapper for SweetAlert's fantastic status icons. This wrapper is intended for users who are interested in just the icons. For the standard SweetAlert modal with all of its bells and whistles, you should probably use Vue-SweetAlert 2

Demo: https://vue-sweetalert-icons.netlify.com/

Download: https://github.com/JorgenVatle/vue-sweetalert-icons/archive/master.zip

2. vue-svg-transition

Create 2-state, SVG-powered animated icons.

Demo: https://codesandbox.io/s/6v20q76xwr

Download: https://github.com/kai-oswald/vue-svg-transition/archive/master.zip

3. Vue-Awesome

Awesome SVG icon component for Vue.js, with built-in Font Awesome icons.

Demo: https://justineo.github.io/vue-awesome/demo/

Download: https://github.com/Justineo/vue-awesome/archive/master.zip

4. vue-transitioning-result-icon

Transitioning Result Icon for Vue.js

A scalable result icon (SVG) that transitions the state change, that is the SVG shape change is transitioned as well as the color. Demonstration can be found here.

A transitioning (color and SVG) result icon (error or success) for Vue.

Demo: https://transitioning-result-icon.dexmo-hq.com/

Download: https://github.com/dexmo007/vue-transitioning-result-icon/archive/master.zip

5. vue-zondicons

Easily add Zondicon icons to your vue web project.

Demo: http://www.zondicons.com/icons.html

Download: https://github.com/TerryMooreII/vue-zondicons/archive/master.zip

6. vicon

Vicon is an simple iconfont componenet for vue.

iconfont
iconfont is a Vector Icon Management & Communication Platform made by Alimama MUX.

Download: https://github.com/Lt0/vicon/archive/master.zip

7. vue-svgicon

A tool to create svg icon components. (vue 2.x)

Demo: https://mmf-fe.github.io/vue-svgicon/v3/

Download: https://github.com/MMF-FE/vue-svgicon/archive/master.zip

8. vue-material-design-icons

This library is a collection of Vue single-file components to render Material Design Icons, sourced from the MaterialDesign project. It also includes some CSS that helps make the scaling of the icons a little easier.

Demo: https://gitlab.com/robcresswell/vue-material-design-icons

Download: https://gitlab.com/robcresswell/vue-material-design-icons/tree/master

9. vue-ionicons

Vue Icon Set Components from Ionic Team

Design Icons, sourced from the Ionicons project.

Demo: https://mazipan.github.io/vue-ionicons/

Download: https://github.com/mazipan/vue-ionicons/archive/master.zip

10. vue-ico

Dead easy, Google Material Icons for Vue.

This package's aim is to get icons into your Vue.js project as quick as possible, at the cost of all the bells and whistles.

Demo: https://material.io/resources/icons/?style=baseline

Download: https://github.com/paulcollett/vue-ico/archive/master.zip

I hope you like them!