slidevjs / slidev

Presentation Slides for Developers
https://sli.dev
MIT License
31.94k stars 1.26k forks source link

The code inside the component will be executed twice #1697

Closed userzeor closed 1 week ago

userzeor commented 1 week ago

/components/Counter.vue组件里面的代码

<script setup lang="ts">
import { ref } from 'vue'

const props = defineProps({
  count: {
    default: 0,
  },
})

console.log('sssssssssssssssssssssssssssssssss');

const counter = ref(props.count)
</script>

<template>
  <div flex="~" w="min" border="~ main rounded-md">
    <button
      border="r main"
      p="2"
      font="mono"
      outline="!none"
      hover:bg="gray-400 opacity-20"
      @click="counter -= 1"
    >
      -
    </button>
    <span m="auto" p="2">{{ counter }}</span>
    <button
      border="l main"
      p="2"
      font="mono"
      outline="!none"
      hover:bg="gray-400 opacity-20"
      @click="counter += 1"
    >
      +
    </button>
  </div>
</template>

在使用组件的页面刷新console.log会执行两次

KermanX commented 1 week ago

This is the expected behavior. <script setup> block will be executed each time an instance of the component is created. In Slidev, the slide component can have two instances: one in the main play view, and one in the slides overview.

If you want the code to execute only once, you can add another <script> block without setup.

userzeor commented 1 week ago

Thank you for your answer