Home > database >  vue2.7 v-if not working with script setup, does vue2.7 above not support this syntax?
vue2.7 v-if not working with script setup, does vue2.7 above not support this syntax?

Time:09-14

<template>
  <div>
    <button @click="handleClick">toggle</button>
    <span v-if="isToggled()">
      hidden message
    </span>
  </div>
</template>

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

const sets = ref<Set<number>>(new Set())

const isToggled = computed(() => () => sets.value.has(1))

function handleClick() {
  sets.value.add(1)
}
</script>

expect: click the button and show the hidden message current: nothing happened...

Vue version: 2.7.7 vite: 3.0.2 typescript: 4.7.4

The basic npm init vue@2 project, and run above code in App.vue with npm run dev

CodePudding user response:

okey... I realized that vue2.7.x is not use Proxy yet, so Set is not supported with reactivity.

solution: just add a reactive data as condition...

<template>
  <div>
    <button @click="handleClick">toggle</button>
    <span v-if="isToggled()">
      hidden message
    </span>
  </div>
</template>

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

const sets = ref<Set<number>>(new Set())
const fake = ref<number>(1)


const isToggled = computed(() => () => fake.value && sets.value.has(1))
// same as function isToggled() { ... }

function handleClick() {
  fake.value  
  sets.value.add(1)
}
</script>

CodePudding user response:

Since Set are not reactive in Vue 2.7, you could try the following workaround :

<template>
  <div>
    <button @click="handleClick">toggle</button>
    <span v-if="isToggled">
      hidden message
    </span>
  </div>
</template>

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

const sets = ref<Set<number>>(new Set())

const isToggled = ref(false)

function handleClick() {
  sets.value.add(1)
  isToggled.value=sets.value.has(1)
}
</script>

Old Note for Vue 3:

The computed properties are used as normal variables without using brackets () :

    <span v-if="isToggled">
      hidden message
    </span>

and remove the extra ()=> in computed callback :

const isToggled = computed(()  => sets.value.has(1))

The computed property that returns a function is used when there's an argument passed, otherwise use a normal one :

    <span v-if="isToggled(1)">
      hidden message
    </span>
const isToggled = computed(() => (n)  => sets.value.has(n))
  • Related