0

I have a functional component:

export default defineComponent({
  name: 'MovieOverview',
  components: {
    ExpandedMovieInformation,
  },
  setup() {
    let toggleValue = false;

    const toggleExpandedMovieInformation = (moviex: Movie) => {
      toggleValue = !toggleValue;
      console.log(toggleValue)
    };

    return {
      toggleValue,
      toggleExpandedMovieInformation,
    };
  },
});

<template>
  <div>
    <button v-on:click='toggleExpandedMovieInformation'>click</button>
    {{ toggleValue }}
  </div>
</template>

When I click the button the console.log does log the change, but the toggleValue in the template stays the same value: false.

1 Answer 1

3

Right now the toggleValue variable has no reactivity. You should use ref() or reactive() in order to make it reactive so the view re-renders every time changes are made into that property.

So you should do something like this:

import { ref } from 'vue'

export default defineComponent({
  name: 'MovieOverview',
  components: {
    ExpandedMovieInformation,
  },
  setup() {
    let toggleValue = ref(false);

    const toggleExpandedMovieInformation = (moviex: Movie) => {
      // now you'll have to access its value through the `value` property
      toggleValue.value = !toggleValue.value; 
      console.log(toggleValue.value)
    };

    return {
      toggleValue,
      toggleExpandedMovieInformation,
    };
  },
});

<template>
  <div>
    <button v-on:click='toggleExpandedMovieInformation'>click</button>
    <!-- You DON'T need to change toggleValue to toggleValue.value in the template -->
    {{ toggleValue }}
  </div>
</template>

Check the docs for more info about ref and reactive.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah I was close. I tried that but tried to set the changed toggle value directly on the toggleValue which gives an error since that property is a ref I can't set a boolean directly on it. But had to set it on the value member that toggleValue ref propertie.
each value that's being used in the template that can be changed has to be a reference() or a ref() instance?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.