【Vue & JavaScript & Css】Multiple class name duplication problem(js/jq原生导致多个类名重复问题)

在这里插入图片描述

博主:_LJaXi Or 東方幻想郷
专栏: 写代码遇到的文题
开发工具:Vs Code

我竟然在 Vue 里操作原生

组件 s-select

<template>
  <div class="custom-dropdown">
    <button class="dropdown-toggle">选择一个选项 <i class="up-icon"></i></button>
    <ul class="dropdown-menu">
      <li>选项</li>
    </ul>
  </div>
</template>

<script>
import './index.css';
import { showSelectItem } from './dom.js';
export default {
  name: 's-select',
  mounted() {
    showSelectItem();
  },
};
</script>

dom.js

export const showSelectItem = () => {
  let selectState = false;
  $('.dropdown-toggle').on('click', function() {
    $('.dropdown-menu')[0].style.display = selectState ? 'none' : 'block';
    selectState = !selectState;
  });
};

功能是 点击button,会下拉出一个 select-item 下拉框,结果运行时,有多个 <s-select></s-select>, 所以就会有很多 className 重复,导致成为一次性组件

进行修改

使用 Vue 事件绑定操作组件的 ref 属性中的 style
使用ref属性可以为DOM元素或组件指定一个唯一的引用标识符

修改后的代码

<template>
  <div class="custom-dropdown">
    <button class="dropdown-toggle" @click="toggleDropdown">
      选择一个选项 <i class="up-icon"></i>
    </button>
    <ul class="dropdown-menu" ref="dropdownMenu">
      <li>选项</li>
    </ul>
  </div>
</template>

<script>
import './index.css';
export default {
  name: 's-select',
  mounted() {
    this.showSelectItem();
  },
  methods: {
    toggleDropdown() {
      this.$refs.dropdownMenu.style.display = this.$refs.dropdownMenu.style.display === 'none' ? 'block' : 'none';
    },
    showSelectItem() {
      this.$refs.dropdownMenu.style.display = 'none';
    }
  }
};
</script>

Vue与原生JavaScript之间存在一些差异,虽然在某些情况下仍然可以使用原生JavaScript进行DOM操作,并不是极力不推荐

如果想在 Vue 中实现以上类似的功能,可在 className 中使用 hash code…

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星光菌子Official

你真是个富哥

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值