Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Support optional chaining in vuejs

I have created vue and electron app using @vue/cli-service 4.2 in that I am facing a issue of optional chaining.

I can't use ? for validating the condition like (@babel/plugin-proposal-optional-chaining)

eg. a?.b?.c its means it check weather a exist then check for b otherwise return false same as template expression in angular.

Any one have idea how to configure optional chaining in vuejs.

like image 952
Hardik Kothari Avatar asked May 13 '20 09:05

Hardik Kothari


1 Answers

One quick update is that Vue 3 comes bundled with support for optional chaining.

To test you can try compiling the below Vue component code.

<template>
  <div id="app" v-if="user?.username">
    @{{ user?.username }} - {{ fullName }} <strong>Followers: </strong>
    {{ followers }}
    <button style="align-self: center" @click="followUser">Follow</button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'App',
  props: {
    test: Object
  },
  data() {
    return {
      followers: 0,
      user: {
        id: 1,
        test: {},
        username: '_sethAkash',
        firstName: undefined,
        lastName: 'Seth',
        email: '[email protected]',
        isAdmin: true
      }
    }
  },
  computed: {
    fullName(): string {
      //
      return `${this?.test?.firstName} ${this?.user?.lastName}`
    }
  },
  methods: {
    followUser: function () {
      this.followers += 1
    }
  },
  watch: {
    followers(newFollowerCount, oldFollowerCount) {
      if (oldFollowerCount < newFollowerCount) {
        console.log(`${this?.user?.username} has gained a follower!`)
      }
    }
  },
  mounted() {
    this.followUser()
  }
})
</script>
like image 179
Akash Kumar Seth Avatar answered Sep 20 '22 23:09

Akash Kumar Seth