Pages

Create Vue.js application API

 In this article, we have listed easy ways to create Vue API. Read this full article, to understand the instances better. Install Vue in your system, if you haven’t already. This will be integrated into your Vuejs project that will allow you to build a basic Vue app. 

# 1: createApp()

Create an app instance


Enter the following code

function createApp(rootComponent: Component, rootProps?: object): App


Example:

Use code with inline root component:

import { createApp } from 'vue'


const app = createApp({

  /* root component options */

})


 Use with imported component:

import { createApp } from 'vue'

import App from './App.vue'


const app = createApp(App)

# 2: createSSRApp()

Use SSR Hydration mode to create an app instance. The usage is the same as createApp()

# 3: app.mount()

Use the corner element to mount the app instances. 


Enter the following code

interface App {

  mount(rootContainer: Element | string): ComponentPublicInstance

}


Example

import { createApp } from 'vue'

const app = createApp(/* ... */)


app.mount('#app')


You can also mount to DOM element

app.mount(document.body.firstChild)

# 4: app.unmount()

Unmount all the mounted app instances this will trigger the unmount lifecycle hooks for all kinds of components in the app’s component tree. This will help you integrate API into your Vue application. 


Enter the following code

interface App {

  unmount(): void

}

# 5: app.provide()

Enter the value which can be used in all descendant components within the app.


Enter the following code

interface App {

  provide<T>(key: InjectionKey<T> | symbol | string, value: T): this

}


Example

import { createApp } from 'vue'


const app = createApp(/* ... */)


app.provide('message', 'hello')


Inside a component in the app

export default {

  inject: ['message'],

  created() {

    console.log(this.message) // 'hello'

  }

}


# 6: app.component()

Create Vuejs API with this component. While passing both a component definition and name string, register a global component. It may retrieve an already one in case the name is passed. 


Enter the following code

interface App {

  component(name: string): Component | undefined

  component(name: string, component: Component): this

}


Example

import { createApp } from 'vue'


const app = createApp({})


// register an options object

app.component('my-component', {

  /* ... */

})


// retrieve a registered component

const MyComponent = app.component('my-component')

# 7: app.directive()

This Vuejs API will make your app more interactive. In case you are passing both directive definition and name string, register a global custom directive. It might retrieve an already registered one only if the name is passed.


Enter the following code

interface App {

  directive(name: string): Directive | undefined

  directive(name: string, directive: Directive): this

}


Example

import { createApp } from 'vue'


const app = createApp({

  /* ... */

})


// register (object directive)

app.directive('my-directive', {

  /* custom directive hooks */

})


// register (function directive shorthand)

app.directive('my-directive', () => {

  /* ... */

})


// retrieve a registered directive

const myDirective = app.directive('my-directive')

#8 app.use()

First install a plugin


Enter the following code

interface App {

  use(plugin: Plugin, ...options: any[]): this

}


Example

import { createApp } from 'vue'

import MyPlugin from './plugins/MyPlugin'


const app = createApp({

  /* ... */

})


app.use(MyPlugin)

#9 app.version

Give the Vue version that your app is created with. It will help you inside plugins, where you might need conditional logic which is based on different versions of Vue. 


Enter the following code

interface App {

  version: string

}


Example

This will help you perform a version check inside a plugin

export default {

  install(app) {

    const version = Number(app.version.split('.')[0])

    if (version < 3) {

      console.warn('This plugin requires Vue 3')

    }

  }

}

#9 app.config

Every app instance provides a config element that inculcates the config setting for that app. You can modify its features before mounting your app. 

import { createApp } from 'vue'


const app = createApp(/* ... */)


console.log(app.config)

#10 app.config.errorHandler

This will help you provide a global handler for uncaught errors from within the app. 


Enter the following code

interface AppConfig {

  errorHandler?: (

    err: unknown,

    instance: ComponentPublicInstance | null,

    // `info` is a Vue-specific error info,

    // e.g. which lifecycle hook the error was thrown in

    info: string

  ) => void

}


Example

app.config.errorHandler = (err, instance, info) => {

  // handle error, e.g. report to a service

}

#11 app.config.warnHandler

Provide a custom handler from Vue for runtime warnings


Enter the following code

interface AppConfig {

  warnHandler?: (

    msg: string,

    instance: ComponentPublicInstance | null,

    trace: string

  ) => void

}


Example

app.config.warnHandler = (msg, instance, trace) => {

  // `trace` is the component hierarchy trace

}

#11 app.config,.performace

To enable compile, component init, patch and render performance tracing in the browser timeline panel/ devtool performance, set this config to true. Only work in browser and development mode that supports the API name performance.mark.


Enter boolean 

#12 app.config.compilerOptions

Configuration of the runtime compiler options. All the values set on this kind of object will be transferred to the in-browser template compiler and this will affect all components in the config application. Remember that you will also override all these options on a per-component basis using the compileroptions options. 


#app.config.compilerOptions.isCustomElement

This specifies a check method in order to recognize native custom options. 

Enter: (tag: string) => boolean


Example

// treat all tags starting with 'ion-' as custom elements

app.config.compilerOptions.isCustomElement = (tag) => {

  return tag.startsWith('ion-')

}

#app.config.compilerOptions.whitespace

This will allow you to adjust whitespace handling behaviour template


Enter: 'condense' | 'preserve'

Default: 'condense'


Example

app.config.compilerOptions.whitespace = 'preserve'

#app.config.compilerOptions.comments

This will allow you to adjust HTML components treatment in templates


Enter: boolean

Default: false


Example

app.config.compilerOptions.comments = true

#13 app.config.globalProperties

It is an object which can be used on any component instance and can be registered on global properties inside the app. 


Enter the following code

interface AppConfig {

  globalProperties: Record<string, any>

}


Usage

app.config.globalProperties.msg = 'hello'


This allows msg to be available inside any component template inside the app, plus on this of any component instance:

export default {

  mounted() {

    console.log(this.msg) // 'hello'

  }

}

#14 app.config.optionMergeStrategies

It is an object for describing merging strategies for custom component options.


Enter the following code

interface AppConfig {

  optionMergeStrategies: Record<string, OptionMergeFunction>

}


type OptionMergeFunction = (to: unknown, from: unknown) => any


Example

const app = createApp({

  // option from self

  msg: 'Vue',

  // option from a mixin

  mixins: [

    {

      msg: 'Hello '

    }

  ],

  mounted() {

    // merged options exposed on this.$options

    console.log(this.$options.msg)

  }

})


// define a custom merge strategy for `msg`

app.config.optionMergeStrategies.msg = (parent, child) => {

  return (parent || '') + (child || '')

}


app.mount('#app')

// logs 'Hello Vue'


In our previous blog we have also talked about firebase authentication for your Vue application. 


Authentication with Vue 3 and Firebase

 


Firebase Authentication is important for your application as it can provide backend services and help authenticate your app users. This Vue Firebase authentication method includes phone numbers, passwords, and other social media authentication options like Facebook, Google, and Twitter. 


In this article, we have included steps to set up Firebase manually, set up Vue, and set up the Firebase projects. The user will sign in and then provide support for password and email authentication.  This article will help you add Firebase to the Vue project. 

Step 1: Setting up Vue

We have already talked about setting up Vue in our previous blogs. You can install Vue CLI and then get to the second step. 

Step 2: Setting up a Firebase project

You need a Gmail account to create a Firebase project. Visit Firebase Google Console and create a Firebase project. 


A new page will open and under the authentication section, click on the sign-in method. And you can get the list of providers Firebase currently supports. 


Next, tap on the Edit icon on the Password/Email provider and switch on Enable toggle


After this, you need to register your app under your newly created Firebase project. Select the Web icon on the overview page under ‘Get started by adding Firebase to your app.’

Step 3: Installing dependencies

Next, use cd into the directory of your project and run the below-given command in order to install all the required dependencies. 


npm i firebase vue-router@4 vuex@next


npm allows you to interact with Firebase

Vue Router is the router for Vue

Vuex describes the state management library for Vue.


Step 4: Integrate Firebase with Vue

Import the Firebase package in the main.js file and configure this file to use the app credentials that we already noted from the Firebase console. 


Create a file named firebaseConfig.js in the src folder and then add the app credentials which will be similar to the following code. 


// Import the functions you need from the SDKs you need

import { initializeApp } from "firebase/app";

import { getAuth } from 'firebase/auth'




const firebaseConfig = {

  apiKey: process.env.VUE_APP_FIREBASE_API_KEY,

  authDomain: process.env.VUE_APP_FIREBASE_AUTH_DOMAIN,

  databaseURL: process.env.VUE_APP_FIREBASE_DATABASE_URL,

  projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID,

  storageBucket: process.env.VUE_APP_FIREBASE_STORAGE_BUCKET,

  messagingSenderId: process.env.VUE_APP_FIREBASE_MESSAGING_SENDER_ID,

  appId: process.env.VUE_APP_FIREBASE_APP_ID,

  measurementId: process.env.VUE_APP_FIREBASE_MEASUREMENT_ID

};


// Initialize Firebase

const app = initializeApp(firebaseConfig);


//initialize firebase auth

const auth = getAuth()



export { app, auth }


Replace the firebaseConfig vales with the Firebase credentials. 

Create the components

Now, you can create the required components for your project. Run the below-given command in the src/components directory to create the components. 


touch Register.vue Login.vue Dashboard.vue Navbar.vue

 

Add the routing to the project

Prior to working on your vuejs components, first add the routes that your app will have. In the src directory, create a new routes folder. Add index.js file and edit this file from the following code. 


import { createRouter, createWebHistory } from 'vue-router'

import Login from '../views/Login.vue';

import Register from '../views/Register.vue';

import Dashboard from '../views/Dashboard.vue';



const routes = [

        {

        path: '/login',

        name: 'login',

        component: Login

    },

    {

        path: '/register',

        name: 'Register',

        component: Register

    },

    {

        path: '/',

        name: 'Dashboard',

        component: Dashboard

    }

]



const router = createRouter({

    history: createWebHistory(),

    routes

  })


  export default router     


Now, replace App.vue file content with the <router-view/> tag. 


<template>

  <div>

    <main class="py-4">

      <router-view></router-view>

    </main&gt;

  </div>

</template>


<script>

export default {

};

</script>


Managing state with Vuex

In the src directory, create a store.js file and add the below given code to the file. 


import { createStore } from 'vuex'


const store = createStore({

})


// export the store

export default store


At first, we will define the state with a user object which has the information about the logged user. 


state: {

  user: {

    loggedIn: false,

    data: null

  }

},


The loggedIn property carries a default value of false, and acts as a boolean that tells us whether the user is authenticated or not. In the data property, you will see all the information about the logged-in user. 


getters: {

    user(state){

      return state.user

    }

  },


Here we have described a simple getter named user which returns the user object from the state. 


mutations: {

  SET_LOGGED_IN(state, value) {

    state.user.loggedIn = value;

  },

  SET_USER(state, data) {

    state.user.data = data;

  }

}


Mutation enables us to make changes to the state. Here we’ve defined two mutations. 


actions: {

      async register(context, { email, password, name}){

          const response = await createUserWithEmailAndPassword(auth, email, password)

          if (response) {

              context.commit('SET_USER', response.user)

              response.user.updateProfile({displayName: name})

          } else {

              throw new Error('Unable to register user')

          }

      },


      async logIn(context, { email, password }){

        const response = await signInWithEmailAndPassword(auth, email, password)

        if (response) {

            context.commit('SET_USER', response.user)

        } else {

            throw new Error('login failed')

        }

    },


    async logOut(context){

        await signOut(auth)

        context.commit('SET_USER', null)

    },


    async fetchUser(context ,user) {

      context.commit("SET_LOGGED_IN", user !== null);

      if (user) {

        context.commit("SET_USER", {

          displayName: user.displayName,

          email: user.email

        });

      } else {

        context.commit("SET_USER", null);

      }

  }

  }


Registering users in Firebase

Here you will learn to register users and store their information on Vue Firebase. Replace src/component/Register.vue with the below-given code. 


<template>

  <div class="container">

    <div class="row justify-content-center">

      <div class="col-md-8">

        <div class="card">

          <div class="card-header">Register</div>

          <div class="card-body">

            <div v-if="error" class="alert alert-danger">{{error}}</div>

            <form action="#" @submit.prevent="Register">

              <div class="form-group row">

                <label for="name" class="col-md-4 col-form-label text-md-right">Name</label>


                <div class="col-md-6">

                  <input

                    id="name"

                    type="name"

                    class="form-control"

                    name="name"

                    value

                    required

                    autofocus

                    v-model="name"

                  />

                </div>

              </div>


              <div class="form-group row">

                <label for="email" class="col-md-4 col-form-label text-md-right">Email</label>


                <div class="col-md-6">


Here, we’ve created a normal bootstrap form for registering users within <template></template> tag. 


Logging in users

This will help you understand the code enabling users to log in. Edit the Login.vue component that you created earlier. 


<template>

  <div class="container">

    <div class="row justify-content-center">

      <div class="col-md-8">

        <div class="card">

          <div class="card-header">Login</div>

          <div class="card-body">

            <div v-if="error" class="alert alert-danger">{{error}}</div>

            <form action="#"  @submit.prevent="Login">

              <div class="form-group row">

                <label for="email" class="col-md-4 col-form-label text-md-right">Email</label>


                <div class="col-md-6">

                  <input

                    id="email"

                    type="email"

                    class="form-control"

                    name="email"

                    value

                    required

                    autofocus

                    v-model="email"

                  />

                </div>

              </div>


              <div class="form-group row">

                <label for="password" class="col-md-4 col-form-label text-md-right">Password</label>


                <div class="col-md-6">

                  <input

                    id="password"

                    type="password"

                    class="form-control"

                    name="password"

                    required

                    v-model="password"

                  />

                </div>

              </div>


              <div class="form-group row mb-0">

                <div class="col-md-8 offset-md-4">

                  <button type="submit" class="btn btn-primary">Login</button>

                </div>

              </div>

            </form>

          </div>

        </div>

      </div>

    </div>

  </div>

</template>


<script>

import { ref } from 'vue'

import { useStore } from 'vuex'

import { useRouter } from 'vue-router'


export default {

  name: "LoginComponent",

    setup() {

    const email = ref('')

    const password = ref('')

    const error = ref(null)


    const store = useStore()

    const router = useRouter()


    const Login = async () => {

      try {

        await store.dispatch('logIn', {

          email: email.value,

          password: password.value

        })

        router.push('/')

      }

      catch (err) {

        error.value = err.message

      }

    }

    return { Login, email, password, error }

  }

};

</script>


And when the user submits their form, the Login function is invoked which handles the actual registration of the user on Firebase. 


const Login = async () => {

      try {

        await store.dispatch('logIn', {

          email: email.value,

          password: password.value

        })

        router.push('/')

      }

      catch (err) {

        error.value = err.message

      }

    }















Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...