Is it possible that the v-if directive is not functioning properly with the script setup in vue2.7? Have the syntax requirements changed in vue2

<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>

anticipated outcome: click the button and display the hidden message current result: nothing occurred...

Vue version: 2.7.7 vite: 3.0.2 typescript: 4.7.4

Created a basic Vue project using npm init vue@2, then inserted the above code into App.vue and executed with npm run dev

Answer №1

Alright... I recently discovered that vue2.7.x does not currently utilize Proxy, resulting in Set not being reactive.

Here's the workaround: simply introduce a reactive data as a 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>

Answer №2

When working in Vue 2.7, you may encounter reactivity issues with Set. Here is a workaround to try:

<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>

Note for Vue 3 users:

In Vue 3, computed properties are utilized as regular variables without parenthesis ():

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

Simply remove the extra ()=> in the computed callback like so:

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

If your computed property requires an argument when used, define it as a function:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Various filters have been utilized on an array of objects

Within one of my Vue components, the code structure is as follows: <li class="comment" v-for="comment in comments"> ... </li> Accompanied by a computed method: computed: { comments() { // Here lies the logic for filtering comment ...

Creating a dropdown menu in Vue.js with a nested array

Upon receiving a response from the Zoho API, I am faced with an array structured as follows: { "response": { "result": [{ "4076840000001": [ { "Department": "Department 1", " ...

The Vue.js error message "Unable to access property 'array_name' as it is undefined" indicates an issue with

I'm currently working on fetching data using Axios requests and storing it in an array. Below is the code I have been using: props: [ 'products', ], data: function () { return { algolia: '', pro ...

Encountering difficulty when attempting to load a Vue component within a Blade file in Laravel 8

I successfully loaded Vue components in previous versions of Laravel by following these steps: In app.js located within resources/app.js, I declared the component like so: Vue.component('upload-menu', require('./components/UploadMenu.vue&ap ...

Adding Typescript to a Nativescript-Vue project: A step-by-step guide

Struggling over the past couple of days to configure Typescript in a basic template-generated Nativescript-Vue project has been quite the challenge. Here's my journey: Initiated the project using this command: ERROR in Entry module not found: Erro ...

Nuxt3 encountered a request error for an unhandled 500 fetch failure at the http://localhost:3000/__nuxt_vite_node__/manifest url

Can you help me understand this error? https://i.stack.imgur.com/0FGa4.png Without making any adjustments to my code, the app builds successfully. However, when running it on dev mode, the following error appears: npm run dev I have attempted rebuilding ...

Update tailwindcss color dynamically according to user input within Vue3/Nuxt3

I am currently exploring a method to allow users to specify the primary color of a website. When defining my Tailwind classes, I aim to utilize something like bg-primary-600 instead of directly inputting a color. This way, if the value for primary changes, ...

The 'name' property of Axios and Vuex is not defined and cannot be read

When making a call to axios in my mounted function to retrieve profile data, I send the payload to the 'set_account' Vuex store upon success. To access this data, I utilize MapGetters (currentAccount) in computed properties. However, when tryin ...

What is the process for importing a component along with all its dependencies?

I have a script where I am attempting to import a component and utilize its dependencies in the template. Specifically, I am looking to locally register a component FooComponent and use SharedComponent within the template of BarComponent. In Angular 2, one ...

What is the process for converting a UTC datetime string into the local timezone of users?

I am utilizing Laravel 5.7 for the API and Vue for the frontend development. The API response includes a user's last seen timestamp in UTC format by default, like this: last_seen: "2019-04-17 05:20:37". Laravel API code: $user_details = array( ...

Using the <pre> tag with Vue.js in v-html allows for displaying pre

When using v-html to display content retrieved via AJAX, I encountered an issue with the "pre" tag not rendering as expected. Here is my component setup: <div v-html="content"></div> For example, the content includes: <h1>Title</h1 ...

Vuetify Container with a set maximum width that remains fixed

I recently started developing a web application using Vue.js and Vuetify (https://vuetifyjs.com/en/). Currently, I have a basic layout with 3 columns. However, I noticed that the width of these columns is restricted to a maximum of 960px due to some defau ...

Tips for incorporating a conditional statement within a vue.js :attr

In the input field, I have set a minimum and maximum value. Sometimes, the maximum value is incorrectly set to 0 when it should be disabled or set to a higher number like 150. What would be the most effective way to create a conditional statement to addre ...

Trouble retrieving data using component props

I am currently facing an issue with displaying data from the API in a component. The request is being made from the parent page, but the loop to display the data is within the child component. Unfortunately, the data is not showing up on the parent page as ...

Identifying separator when v-carousel is selected

How can I detect when a delimiter is clicked on a v-carousel? https://i.stack.imgur.com/9M1XL.jpg ...

Guide on structuring Vue so that all pages have a consistent header and navigation, while still allowing for standalone pages like a registration form

Currently, my Vue app is structured like this: https://i.stack.imgur.com/bMqxX.png In this layout, the login Vue is live under VContent. Certain parts of the header and nav are disabled based on the authentication state. For instance, the logout button i ...

Is there a way for me to showcase the latitude and longitude retrieved from JSON data on a Google Map using modals for each search result in Vue.js?

After receiving JSON data with search results, each containing latitude and longitude coordinates, I am attempting to display markers on a Google map modal when clicking "View Map". However, the code I'm using is not producing the desired outcome. Th ...

Navigate back to the previous route within the Vue router hierarchy

In my Vue application, I have a Settings page with child routes such as settings/user, settings/addUser, etc. I am looking to implement a back button that when pressed, takes the user back to the specific page they visited within the Settings section. Usin ...

Achieving JSX rendering in Vue.js with TypeScript starting from a basic CLI setup along with the JSX package integration

The Setup I have set up a new project using the vue-cli, where I manually selected certain features including Babel, TypeScript, Vuex, and Linter / Formatter. Additionally, I chose version 2.x and opted to use Babel alongside TypeScript for modern mode an ...

Tips for showcasing the content of a variable

Extracts information from a collection: const pageTitles = { homePage: 'Main' ... } export default pageTitles When I attempt to display it like this: <div><span>{{pageTitles.homePage}}</span></div> everything funct ...