Vadim Tomashevsky
Vadim Tomashevsky

Reputation: 338

Vue js - is that right to put all my code in watch?

I Have component A and Component B in component A i have an API call.

when i passing info to my component b:

<B :structuresMetaData="structureTree"></B>

Inside mounted the variable structuresMetaData the length is 0

and inside the watch the length is 1.

my issue that mounted appear before the watch.

is it would be right to put all my code in watch ? if not what is the solution ?

Upvotes: 0

Views: 102

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

It looks like structureTree is being changed after <B> is created/mounted.

You have two options depending on your use case:

The first option is to defer the creation of <B> until your data is loaded. This way you don't need <B> to watch for changes to the prop and the prop will be fully populated in the created/mounted hook. This is the simpler approach.

Assuming structureTree is initially an empty array:

<B
  v-if="structureTree.length > 0"
  :structuresMetaData="structureTree"
/>
created() {
  // this.structuresMetaData is a non-empty array here
}

I usually initialize my data with null so that I can distinguish between "not loaded" and "loaded" (where "loaded" can actually be an empty array if the data I fetched from the API was empty).

The second way is using a watcher in <B> to react to changes to the prop. You will need to do this method if the bound prop might change multiple times and you need <B> to update in some way to that change.

watch: {
  structuresMetaData(value) {
    // React to the change, load secondary data, etc
  }
}

What exactly are you doing in <B> that requires a watcher? It's best to avoid explicit watchers if you can avoid them because it usually means you are copying data around and it gets messy when you don't have a single source of truth. Use pure computed properties whenever you can if you just want to transform the data in some way.

Upvotes: 1

Related Questions