Options: Changing Options
What are we learning here?
┌──────────────┐
│ Change │
│ Options │
└───────┬──────┘
┌──────────────┐ ┌──────────────────────────────────────────┼──────┐
│ Loading │ │ Component │ │
│ Component │ │ │ │
│ ┌──────────┐ │ │ ┌──────────────────┐ ╔════▼════╗ │
│ │ options ├─┼─┼─Transform───►│ Received Options ├──►║ Final ║ │
│ └──────────┘ │ │ (optional) └────────▲─────────┘ ║ Options ║ │
│ │ │ Merge ╚════╤════╝ │
└──────────────┘ │ ┌────────┴─────────┐ ┌────▼────┐ │
│ │ Static Defaults │ │ ! Watch │ │
│ └──────────────────┘ └─────────┘ │
└─────────────────────────────────────────────────┘
- Options can be changed via the public component property
options
- Options changes can be watched with
watchEffect
orwatch
Now it's important to know that the options of a component are "reactive vue objects". This means
that changes to these options can be observed and responded to using the watchEffect
and watch
methods of the vue
package.
The only thing we need to change in our example is to include the two lines with the assignment of
the values in a watchEffect
function:
src/demo/apps/component-basics/content.js
Now we add code to change the value of this.options.myOption1
periodically in our application,
where we have instatiated the widget. We use the public property options
of the widget to change a
single option.
The public property options
can also be used to change multiple options at once. Only options that
will be set there will be changed. All other options are not affected:
src/demo/apps/component-basics/index.js
Now the value of myOption1
will change every 2 seconds.
Do not try to change deep options directly
Even if this in some cases would work (it do not work for the example above):
You should never change options this way. To update the options this pattern is always preferable:
The first approach can lead to strange behaviour and could not work at all:
- If the component have a
watch
exactly for thisoption1
it will not work. - If the component have defined a
$map
in its defaults it will not work. You could of course use the correct namespace likecomponentInstance.options["@someNamespace"].subNamespace.option1 = "NewValue1"
but then the problem from the first point still remains.