[Vuejs]-Is it possible to write JavaScript directly in vue js?

3πŸ‘

βœ…

The very purpose to use Vue is to leverage its features for handling this type of logic reactively, Following is the snippet which can be used(vue 3 options api)

<template>
  <div class="customers-page">
    <h2>Customers</h2>

    <button type="add" class="add-button" @click="openpopup">Add</button>
    <!-- onclick="openpopup()" -->
    <div class="popup" :class="popupToggle ? 'open-popup' : ''">
      <h3>Input the following information</h3>

      <button type="add-customer" class="submit-customer-button" @click="closepopup">Submit</button>
      <!-- onclick="closepopup()" -->
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      popupToggle: false,
    };
  },
  methods: {
    openpopup() {
      this.popupToggle = true;
    },
    closepopup() {
      this.popupToggle = false;
    },
  },
};
</script>

Here the popup view is maintained by a state variable popupToggle, if you want to use something similar to id then you should go through refs here

πŸ‘€Kaneki21

0πŸ‘

When you use frameworks like Vue / React etc, using the native DOM is discourage (basically those .getElementById, .classlist.add or similar). One main reason is security, anyone can go to inspect and do DOM manipulations.

If you want to avoid the Options API boilerplate, you can use Composition API, which is similar to what you are doing.

Besides, if you are using conditional rendering, v-if is recommended instead of class binding, because the elements are not rendered if it is false.

<template>
   <div class="customers-page">
      <h2>Customers</h2>
      <button type="add" class="add-button" @click="openPopup()">Add</button>
      <div v-if="isShowPopup" class="popup">
          <h3>Input the following information</h3>
          <button type="add-customer" class="submit-customer-button" @click="closePopup()">Submit</button>
      </div>  
   </div>
</template>

<script setup>
import { ref } from 'vue' 
const isShowPopup = ref(false)// acts similar to options api data block

// here I am using arrow functions
const openPopup = () => {
  isShowPopup.value = true // in composition API, instead of using this., you use .value
}

const closePopup = () => {
  isShowPopup.value = false
}

</script>
πŸ‘€Remicaster

Leave a comment