Vue's reactivity in Vue 3 is exhibiting strange behavior with boolean data

Currently, I am attempting to modify a boolean variable. Upon the initial page load, everything works as expected. However, upon reloading the page, the variable gets updated locally within the method but not in the global data section. As a result, an error continues to appear in the console stating: "Uncaught (in promise) TypeError: Cannot read property 'value' of undefined at invokeDirectiveHook"

I'm wondering if there is something crucial that I may have overlooked?

<template>
  <p>Value: {{ val }}</p>
  <button @click="changeMe">Click Me</button>
</template>

<script>
import { ref } from 'vue';

export default {
  data() {
    return {
      val: ref(false);
    },
  },
  methods: {
    changeMe() {
      this.val = !this.val;
    }
  }
}
</script>

Answer №1

it's important to keep the options API separate from the composition API

Options API

Vue.createApp({
  data() {
    return {
      val: false
    }
  },
  methods: {
    changeMe() {
      this.val = !this.val
    }
  }
}).mount('#demo')
<script src="https://unpkg.com/vue@next"></script>

<div id="demo" class="demo">
  <p>Value: {{ val }}</p>
  <button @click="changeMe">Click Me</button>
</div>

Composition API

const { createApp, ref } = Vue;
const app = createApp({
  setup() {
    let val = ref(false)
    
    function changeMe() {
      val.value = !val.value
    }

    return {
      val,
      changeMe
    }
  }
});
app.mount("#app");
<script src="https://unpkg.com/vue@next"></script>
<div id="app">
   <p>Value: {{ val }}</p>
  <button @click="changeMe">Click Me</button>
</div>

Compositions API (short)

// Composition API
<template>
  <p>Value: {{ val }}</p>
  <button @click="changeMe">Click Me</button>
</template>

<script setup>
import { ref } from 'vue'

const val = ref(false)

function changeMe() {
 val.value = !val.value
}
</script>

the <script setup> is now integrated into the latest version 3.2

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

What sets apart these two JavaScript namespaces?

My main goal is to expertly organize my javascript code by eliminating any global elements. I came across two namespace declaration methods in this informative post, and now I'm looking for your input on the advantages and disadvantages of each. ...

What is the process for creating a custom Javascript function that can seamlessly integrate with other Javascript libraries?

Is there a way to create a method that can be linked or chained to jQuery methods and other library methods? For example, consider the following code snippet: var Calculator = function(start) { var that = this; this.add = function(x) { start = start ...

Accessing child value in parent component using React.js

In my project, I have a main Component called [MainLayout] which contains a child component called [ListItems]. The [ListItems] component further has multiple children components called [ListItem]. I am trying to figure out how to extract the value of the ...

Error in Nuxt JS / Vue JS search feature functionality

Recently, I received assistance with creating a search feature for a real estate website. The concept is to have a /properties page showing a list of properties along with a universal search component on every page. This component has an action that direct ...

What is the reasoning behind an empty input value being considered as true?

I am facing an issue with the following code that is supposed to execute oninput if the input matches the answer. However, when dealing with a multiplication problem that equals 0, deleting the answer from the previous calculation (leaving the input empt ...

Invert the motion within a photo carousel

Is there anyone who can assist me with creating a unique photo slider using HTML, CSS, and JS? Currently, it includes various elements such as navigation arrows, dots, and an autoplay function. The timer is reset whenever the arrows or dots are clicked. Ev ...

Implementing a Tri-state Checkbox in AngularJS

I've come across various discussions on implementing a 3-state checkbox with a directive or using CSS tricks (such as setting 'indeterminate=true' which doesn't seem to work). However, I'm curious if there's another method to ...

What is the process for implementing a security rule for sub-maps with unique identifiers in Firebase?

I am looking to implement a security rule ensuring that the quantity of a product cannot go below zero. Client-side request: FirebaseFirestore.instance .collection('$collectionPath') .doc('$uid') .update({'car ...

The Laravel 8/Passport/GuzzleHttp API request successfully returns a status code of 200, however, there is no response

Currently, I am in the process of setting up a login page using Vue.js (front-end) with Laravel 8 (back-end), incorporating Passport and GuzzleHttp. The oAuth/Token functionality has been successfully tested using Insomnia. Additionally, the userData retr ...

Utilizing the request module in Node.js with ExpressJS

Currently, I am in the process of creating a helper method within my code that will handle user authorization. This function, named "usePermissions", is being developed following the React approach but for backend functionality. Upon implementa ...

Redirecting the socket.io client to the Heroku service

Recently, I developed a real-time chat application using socket.io, Node.JS, and express. It was functional on my local server but now I want to connect it to an existing Heroku service instead. How can I achieve this? Once I tried the following code, va ...

Any suggestions on how to secure my socket connection following user authentication in redux?

After onSubmit, userAction.login is called which then dispatches "SUCCESS_AUTHENTICATE" to set the token of the user and socket state in their respective reducers. How can I proceed to trigger socket.emit("authenticate", {token})? ...

Adding a Material UI Tooltip to the header name of a Material UI Datagrid - a step-by-step guide!

I've nearly completed my initial project, but the client is requesting that I include labels that appear when hovering over specific datagrid cells. Unfortunately, I haven't been able to find any solutions on Google for adding a Material UI Tool ...

Organize object properties based on shared values using JavaScript

Check out the JavaScript code snippet below by visiting this fiddle. var name = ["Ted", "Sarah", "Nancy", "Ted", "Sarah", "Nancy"]; var prodID = [111, 222, 222, 222, 222, 222]; var prodName = ["milk", "juice", "juice", "juice", "juice", "juice ...

Encountered an exception while trying to retrieve data with a successful status code of 200

Why is a very simple get() function entering the catch block even when the status code is 200? const { promisify } = require('util'); const { get, post, patch, del } = require('https'); //const [ getPm, postPm, patchPm, deletePm ] = [ ...

Activate a click event on an element using Simple HTML DOM

I need assistance in triggering a click on the element below and then retrieving its innertext. <a class="btn btn-sm btn-default" href="javascript:;" onClick="score(238953,this)">Show result</a> Once the "onClick" event is triggered, the elem ...

Struggling to dynamically append additional textboxes to a <div> element using JavaScript

After spending over 12 hours on this problem, I am completely stuck and frustrated. I have tried countless variations and sought out other solutions to no avail. It should be a simple task. My project involves using JQueryMobile 1.2 along with its dependen ...

What is the process for comparing two objects in TypeScript?

There is a unique class named tax. export class tax { private _id: string; private _name: string; private _percentage: number; constructor(id: string = "", taxName: string = "", percentage: number = 0) { thi ...

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...

display PHP JSON information using jQuery AJAX

I'm completely new to this subject. I have a Json result that looks like the following : { "span": " 1", "numcard": "12", "chan": " Yes", "idle": "Yes", "level": "idle ", "call": "No ", "name": "" } My goal is to ...