vue.jselectronvue-cli-4ecmascript-2020

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.


Solution

  • 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: 'sethakash007@gmail.com',
            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>