Bruno Francisco
Bruno Francisco

Reputation: 4240

Set variable from inside composition file vue

I'm beginning with composition API in Vue and I don't know if I'm breaking some pattern by doing things the way I'm doing.

I would like to set a variable from inside the composition file itself:

GameLogic.ts

export default function () {
  ...
    
  const buildMovieGuessed = (movie: Movie, score: number) => ({ ...movie, score });

  const addNewMovieGuessing = (movie: Movie, score: number) => {
    // The variable moviesGuessed is not being set. In my template it still stays a
    // an empty array
    moviesGuessed = [buildMovieGuessed(movie, score), ...moviesGuessed];

    currentStep.value += 1;
  };

  return {
    originalMovies,
    activeTerm,
    currentStep,
    activeMovie,
    guessingScore,
    moviesGuessed,
    addNewMovieGuessing,
  };
}

From the Vue component I call

GuessMovie.vue

<script lang="ts">
import { defineComponent } from '@vue/composition-api';
import GameLogic from '@/services/composition/game/GameLogic';
import { ValidationObserver } from 'vee-validate';
import BInputWithValidation from '@/components/_buefy/BInputWithValidation.vue';

export default defineComponent({
  components: {
    ValidationObserver,
    BInputWithValidation,
  },
  setup() {
    const {
      originalMovies,
      activeTerm,
      currentStep,
      activeMovie,
      guessingScore,
      moviesGuessed,
      addNewMovieGuessing,
    } = GameLogic();

    return {
      originalMovies,
      activeTerm,
      currentStep,
      activeMovie,
      guessingScore,
      moviesGuessed,
      addNewMovieGuessing,
    };
  },
  methods: {
    onAddNewMovieGuessingClick() {
      // I call the action from here  
      this.addNewMovieGuessing(this.activeMovie.value, this.guessingScore.value);
    },
  },
  created() {
    // @todo: handle the case if there are no movies
  },
});
</script>

How can I set up the variable moviesGuessed from inside the GameLogic.ts so that I can keep the logic in a central place?

Upvotes: 0

Views: 89

Answers (1)

tony19
tony19

Reputation: 138696

When addNewMovieGuessing() reassigns moviesGuessed, you're losing the reference to the original value.

It looks like you're trying to insert the new movie guess into the first position of the moviesGuessed array. You could use Array.prototype.unshift() to do that without losing reactivity:

// BEFORE:
moviesGuessed = [buildMovieGuessed(movie, score), ...moviesGuessed];

// AFTER:
moviesGuessed.unshift(buildMovieGuessed(movie, score));

Upvotes: 1

Related Questions