S
S
Serega_SRG2020-08-05 17:47:08
JavaScript
Serega_SRG, 2020-08-05 17:47:08

How correct is it to overwrite the property?

There is a component whose behavior (conditional rendering) can be determined by different things.
They have their own priority. Props of the path, Props from the parent, the state of some getter in state.
How correct is it to do this:

mounted () {
  if (prop) {
    this.x = 'a'
  }
  if (route) {
    this.x = 'b'
  }
  if (state) {
    this.x = 'c'
  }
}

That is, overwrite the property if there is a higher priority data source?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
0
0xD34F, 2020-08-05
@0xD34F

There are too many if's and assignments. You can add the data to an array and look for a suitable value in it:

const data = [
  [ state, 'c' ],
  [ route, 'b' ],
  [  prop, 'a' ],
].find(n => n[0]);

if (data) {
  this.x = data[1];
}

In addition, it is not clear - what if some of the checked values ​​change after the component has been mounted? You should probably make yours xa computed property.

M
McBernar, 2020-08-05
@McBernar

Let this.x?

A
Aetae, 2020-08-08
@Aetae

You don't need to overwrite. Checked all the conditions and assigned once.
If you need to assign a lot - Object.assignto help you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question