aulia amirullah
aulia amirullah

Reputation: 196

Boolean data seems acting weirdly in vue's reactivity in vue 3

I'm trying to change a variable that has a data type 'boolean'. When the page is first loaded, the data works well. However, when the page is reloaded, the variable is updated locally in the method, but not in the global data section. Therefore in the console, I keep receiving an error "Uncaught (in promise) TypeError: Cannot read property 'value' of undefined at invokeDirectiveHook"

Is there something I've missed?

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

Upvotes: 2

Views: 4502

Answers (1)

wittgenstein
wittgenstein

Reputation: 4482

please don't mix the options API with 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 included in the 3.2 version

Upvotes: 5

Related Questions