typescript 如何在没有可变性的情况下在Vue3组件上实现悬停事件?

hgb9j2n6  于 2023-03-31  发布在  TypeScript
关注(0)|答案(1)|浏览(149)

我试图在自定义导航栏组件上实现hover事件,我总是这样看待实现:

<template>
  <nav @mouseover="hover = true" @mouseleave="hover = false" :class="{ open: hover }">
    <!-- ... -->
  </nav>
</template>

<script setup lang="ts">
defineProps<{hover?: false}>();
</script>

但是,使用vue eslint规则会在此实现中触发vue/no-mutation-props
有没有一种方法可以实现悬停事件并在不改变的情况下更改hover属性值?

s4n0splo

s4n0splo1#

解决方案

const { createApp, ref } = Vue;

const MyComp = {
  setup() {
    const hover = ref(false)
    return { hover }
  },
  template: `
  <nav @mouseover="hover = true" @mouseleave="hover = false" :class="{ open: hover }">
    hover: {{hover}}
  </nav>`
}

const App = { 
  components: { MyComp }
}
const app = createApp(App)
app.mount('#app')
#app { line-height: 2; }
[v-cloak] { display: none; }
nav { background-color: lightgray; padding: 10px;}
nav.open { background-color: lightblue; }
<div id="app" v-cloak>
  <my-comp></my-comp>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

相关问题