Abdullah Ch
Abdullah Ch

Reputation: 2151

How to call a method when the props are passed (for the first time) to a component in Vue.js

<script>
    import _ from "lodash";

    export default {
        name: "QuestionBottom",
        props: {
            currentQuestion: Object,
            nextQuestion: Function,
            increment: Function,
        },
        data() {
            return {
                selectedIndex: null,
                correctIndex: null,
                shuffleArray: [],
                ansArray: [],
            };
        },

        // watch listens for changes to the props
        watch: {
            currentQuestion() {
                this.selectedIndex = null;
            },

            // I want this method to run when props are passed to the component even at the first time
 
            allOptions() {
                console.log("I am second");
                console.log("what's in this.allOptions", this.allOptions);
                this.correctIndex = this.allOptions.indexOf(
                    this.currentQuestion.correct_answer
                );
                console.log("Correct index isss", this.correctIndex);
            },
        },

        computed: {
            allOptions() {
                let allOptions = [
                    ...this.currentQuestion.incorrect_answers,
                    this.currentQuestion.correct_answer,
                ];

                //  console.log("array that is not shuffled is ", allOptions);
                allOptions = _.shuffle(allOptions);
                console.log("shuffled array is", allOptions);
                // console.log("Corect ans is ", this.currentQuestion.correct_answer);
                console.log("I am first");
                return allOptions;
            },
        },

        methods: {
            selectedAns(index) {
                this.selectedIndex = index;
                console.log("Selected answer index", this.selectedIndex);
            },
            submitAnswer() {
                let isCorrect = false;
                if (this.selectedIndex === this.correctIndex) {
                    isCorrect = true;
                }
                this.increment(isCorrect);
            },
        },
    };
</script>

I want my watch region's allOptions() to be run when the props are passed for the first time. Now, I know that watch runs when a method or prop changes but can I run the method from the first time props are passed. Is there any way that I can make this method to run from the point props are passed to the component.

Upvotes: 1

Views: 296

Answers (1)

tony19
tony19

Reputation: 138226

Use the immediate flag of the watch option:

export default {
  watch: {
    allOptions: {
      handler() {
        this.correctIndex = this.allOptions.indexOf(this.currentQuestion.correct_answer);
      },
      immediate: true,
    }
  }
}

demo

Upvotes: 1

Related Questions