Component Props in Vue

Vue enables you to define more than one props against a component. Defining props and passing around values are one of the ways of getting components to react to values passed to them (think arguments), or talk to each other :). See which component communication is effective and how props compare to Vuex Defining prop in a component is simple enough - <!-- Target.vue --> <template> {{ tinyInput }} <!-- display the prop --> </template> <script> export default { props: { tinyInput: { type: String, required: false } } }; </script> You can now call this component from another component/view like so - ...

Reload Component based on Routes in Vue

If two links in your Vue application point to the same view, clicking those links one after the other may not result in data being refreshed from server. Imagine you have the same view for two different links - My account All account Both links will point to Account.vue. You will have a router file like so.. // ./router.js import Vue from "vue"; import Router from "vue-router"; Vue.use(Router); export default new Router({ routes: [ { path: "/my-account", name: "my-account", component: () => import("./views/Account.vue"), props: { authMode: "my" } }, { path: "/all-account", name: "all-account", component: () => import("./views/Account.vue"), props: { authMode: "all" } }, }); Example code for router is picked from the demonstration of how to implement role-based data filters in Vue. ...

Global Variables and Functions in Vue

Vue provides a way to create global variables and functions using Vue.prototype. What do you normally do if you want to create a global variable in Vue? You don’t. Global variables have no place in today’s society You create variables in storage. That’s the purpose of storage You can say the exact same thing about functions. But, what if you have variables that sound silly if they get into something as elegant as Vuex store? Or worse, what if you don’t have a store and you cannot add one since you inherited a stupid-ass Vue project? ...

Delete Element in Array Reactively in Vue

Deleting elements in an array maintains reactivity in Vue when done right. These arrays can be local variables in a component, or state variables in Vuex - the behaviour is the same. Let us consider this example - <template> {{ fruits }} <v-btn @click="deleteFirst"> Delete First </v-btn> <v-btn @click="deleteLast"> Delete Last </v-btn> </template> <script> export default { name: "Farm", data() { return { fruits: ["apple", "orange", "grapes", "pear"] }; }, methods: { deleteFirst() { this.fruits.shift(); // delete last }, deleteLast() { this.fruits.pop(); // delete last } } }; </script> We just use the standard pop and shift to delete elements in the array. This works just fine and UI is reactive to the changes. ...

URL Params in Vue

Why and how would you pass parameters to a Vue application? You might have seen URLs that pass parameters to whatever front-end / back-end logic that is processing them. This will be something akin to - https://myapp.com/accounts/1 https://myapp.com/accounts/1/todo/2 https://myapp.com/accounts?id=1 https://myapp.com/accounts?query=abc&role=my id, query, role are parameters passed in the URL. The receiving function can have access to the parameters and values, and have processing logic based on values. URL params are heavily used in some of the modern headless CMS applications (e.g. Strapi). You can pass a whole lot of stuff against URL and the server has out of the box support to respond to the values. Even in some of the older APIs will have support to referring to a specific resource with id. ...

Reusable Alerts in Vuetify

A common requirement in any data-driven application is to show any alerts including error or warning messages at a standard location within a Vue component. This is easily accomplished using v-alert in Vuetify, but it is a good idea to use it in combination with a snackbar. Consider a typical component Account.vue - <template> <div class="account"> <v-layout row wrap> <v-flex xs12 class="title"> Accounts </v-flex> <v-flex xs12> <AccountList></AccountList> </v-flex> <v-flex xs12> <AccountDetail></AccountDetail> </v-flex> </v-layout> </div> </template> The requirement is to show informational messages, errors or warnings - either from back-end applications or front-end validation messages etc. as a popup alert. ...

Take Full Advantage of Vue Components

When beginning in Vue it may seem easier to create self-contained components, use them in views and call it a day. But Vue components can be much more powerful. Let’s consider an example where you have to create two views - Account and User. Typically, you create an Account.vue view - <template> <div class="account"> <v-layout row wrap> <v-flex xs12 class="title"> Accounts </v-flex> <v-flex xs12> <!-- lot of account fields --> </v-flex> </v-layout> </div> </template> You will repeat the same for Users. Accounts and Users have their distinct set of fields, and one may not find any significant commonality, right? ...

Role-based Data Filters in Vue

I would love for the world to wait for a carefully architected VueJS app. But often it doesn’t. I recently had to quickly implement a role-based filter for a data driven application. And, the experience left me somewhat dizzy. First, the basics - Roles had been implemented in the application as custom logic - back-end server framework had roles defined against users Permissions were used to check access to specific routes of API. Front-end app just did not show irrelevant links We had to implement data-filters - e.g. show only accounts assigned to a sales person, while show all of the company accounts to manager. The rules were defined, but not infinitely scalable like that in a typical CRM app My first design idea was to find the current user role and apply filter in Vuex. ...

Always Create 404 Pages in your Vue App

I create 404 pages as a standard practice in my Vue applications. You need that to manage browser page refreshes and to serve direct URLs for all possible pages in your application. Vue app has two parts - backend API frontend routes (pages) Any and all requests to the server go through our Nginx web server. Nginx will show ‘404: page cannot be found’ error if we try to access any page that does not exist for the webserver. ...

Avoid Vuex Boilerplate Code using Pathify

Vuex is a lot of boilerplate. Consider this user store - //store/user.js import axios from "axios"; export default { namespaced: true, name: "users", state: { users: [], loading: false, error: "" }, mutations: { setUsers(state, users) { state.users = users; }, setLoading(state, loading) { state.loading = loading; }, setError(state, error) { state.error = error; } }, actions: { fetchUsers({ commit, state }, params) { commit("setLoading", true); commit("setError", ""); axios .get("http://myServer.com/api/get-users") .then(({ data }) => { commit("setUsers", data); }) .catch(e => { commit("setError", "Error fetching user records."); }) .finally(commit("setLoading", false)); } } }; Access this store from your view or component - <!-- views/User.vue --> <template> <p v-if="error" class="error">{{error }}</p> <p> {{ users }} </p> </template> <script> import { mapState, mapMutations, mapActions } from "vuex"; export default { computed: { ...mapState("user", ["users", "error"]) // states are now accessible as any other computed property }, methods: { ...mapMutations("user", ["setError"]), ...mapActions("user", ["fetchUsers"]) // actions and mutations from store are now accessible // .. as any other methods }, mounted() { this.fetchUsers(); } }; </script> Getting state within components and invoking mutations is laborious and not-so-pretty. If you want to just set one array ‘users’ you need a mutation (setUsers), a state (users), and an action requiring this state. The views and components dependent on the store will use these states and methods - this is way lot of work. ...