是否可以直接在vue js中编写JavaScript?

e37o9pze  于 2022-11-17  发布在  Vue.js
关注(0)|答案(2)|浏览(104)

新的vuejs。我试图写javascript直接在vue文件。下面是代码。我不断得到以下错误...
编译有问题

70:18  error  'openpopup' is defined but never used   no-unused-vars
 73:18  error  'closepopup' is defined but never used  no-unused-vars

带有脚本的Html:

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

      <button type="add" class="add-button" onclick="openpopup()">Add</button>
      <div class="popup" id="popup">
          <h3>Input the following information</h3>

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

</template>

<script type="application/javascript" >
        let popup = document.getElementById("popup");

        function openpopup(){
            popup.classList.add("open-popup")
        }
        function closepopup(){
            popup.classList.remove("open-popup")
        }
</script>
6ovsh4lw

6ovsh4lw1#

使用Vue的真正目的是利用其特性来React性地处理这种类型的逻辑,以下是可以使用的代码片段(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>

这里,popup视图由状态变量popupToggle维护,如果您希望使用类似于id的内容,则应在此处执行refs

ymdaylpp

ymdaylpp2#

当你使用Vue / React等框架的时候,使用原生DOM是不被鼓励的(基本上是那些.getElementById.classlist.add或类似的)。一个主要的原因是安全性,任何人都可以去检查和做DOM操作。
如果要避免使用Options API样板文件,可以使用Composition API,这与您正在执行的操作类似。
此外,如果您使用的是条件呈现,则建议使用v-if而不是类绑定,因为如果是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>

相关问题