Website reference
Website reference
With svelte, reactivity occurs automatically. In svelte, a single fragment of any component can be dynamically regenerated at any time! Svelte carefully manages each fragment (what is a fragment? That is, "code segment", which refers to any js expression passively managed and re executed by svelte at the appropriate time, that is, when the dependency state changes. Finally, fragments are used to provide the dynamics of our html tags, that is, its reactivity), monitor and re execute them as needed according to the dependency state changes.
Clips can be used in two places
code-snippets
In the js code of the component (in the
//In the following code, as long as the user object changes (the dependency of the code segment), the name and phone will change again $: {name, phone} = user;
html-snippets
Located in the html tag {...} This is usually called interpolation. These operations are heavyweight because they will cause changes to the html DOM!
<p>Hello {name}</p> <p>May we call you at {phone}</p>
Terminology: snippets, code snippets, and html
Fragments refer to any js expression that svelte passively manages and invokes when its dependency state changes
Fragments can be code fragments (reactive declarations and reactive statements)
Or HTML snippets (slots)
The final fragment provides dynamic information in our html tags
Action Trigger
How does svelte determine when to trigger new execution of our code snippet?
svelte listens to the dependency state referenced in each fragment and triggers update execution when the state changes
How does svelte determine state reference changes?
The svete document talks about "assignment is reactive" and "svelte's reactivity is triggered by assignment". Svelte triggers reactivity through assignment semantics (identifying various forms of assignment), which is correct for the local state of the component. The svelte compiler will identify assignments (in various forms) and mark the copied variables as changed (i.e. "obsolete")
There is a big difference whether the assignment target is the original object or the object (including the array)
Original object assignment
For the original object (string, number, Boolean, etc.), it will react only when the value changes. It also combines JavaScript identity semantics (i.e. priorState === nextState)
For example, myNum=(x+y)/2 is marked "obsolete" only when its value actually changes. If the value of 10 is verified first, the calculation result of 10 will not change
object type
It turns out that in svelte, whatever you change the object, the entire object is marked "obsolete", including local component objects, svelte object storage, array object properties, etc. when you change the object, you will notify svelte that the object has changed (by assigning it to itself)
Summary: when the dependency state changes, the code segment execution is triggered. The original type only triggers the reactivity when the value changes, and the object triggers the reactivity of the whole object
Diagnostic log
Simple diagnosis
//previous <p>Hello {name}</p> <p>May we call you at {phone}</p> //current <p>Hello {console.log('Name section fired) || name}</p> <p>May we call you at {console.log('Phone section fired) || phone}</p>
Advanced diagnostics
//createReflectiveCounters.js export defaule function createReflectiveCounter(logMsg){ const {subscribe,set,update} = writable(-1); return { subscribe, monitor(...monitorDependents){ update((count)=>count+1); logMsg&& console.log(logMsg); return ''; }, reset:()=>set(0); } } //call <i>{fooSectionReflexiveCount.monitor() || $foo}</i> //Print to workbench <mark>{$fooSectionCount}:</mark> //Display directly on the page
Call in html
<script> const fooReflexiveCount = createReflectiveCounter('foo section fired'); </script> <!-- diagnostic reporter --> <mark>{$fooReflexiveCount}:</mark> <!-- monitor this section --> <i>{fooReflexiveCount.monitor() || $foo}</i> <!-- reset counts --> <button on:click={fooReflexiveCount.reset}>Reset</button>
● monitoring status change technology (in code snippet)
<script> const fooChangeCount = createReflectiveCounter(); $: fooChangeCount.monitor($foo); </script> <!-- reporter/resetter --> <i>$foo state change counts: {$fooChangeCount}</i> <button on:click={fooChangeCount.reset}>Reset</button>
Create GreetUser.svelte
Case address
t it can be seen from this case that when a single attribute is changed, the html fragment will be re executed. When you click Apply Change on the stand-alone button without attribute change, three html fragments will still be executed. This is because the object is used and the object reference has dependencies. As shown below, svelte marks $user as over time, because any html fragment referencing the object will be re executed. Whether or not. name is referenced
<p>Hello {$user.name}!</p>
svelte's innovative rendering optimization
The above case proves that the listening object html will be reloaded, but this does not mean that the DOM will be re rendered, because actually loading the DOM will produce redundant and unnecessary rendering. Loading DOM updates is expensive. html snippet is re executed in svelte, but it does not mean that DOM updates will be caused.
svelte actually optimizes DOM updates by ensuring that the content actually changes
Incremental update
Since svelte only triggers dom name when the content is actually changed, we focus on the bottom logic p() update method, which is the method of incremental dom update.
//html <p>Hello {$user.name}!</p> //Compilation results //Comments: logical bitwise operators bitwise and (&), bitwise OR (|), bitwise exclusive or (^), non bitwise (~) //Bit operation is the calculation of binary numbers. It is a bit by bit operation of integers. For example, 1 + 1 = 2 is correct in decimal calculation, //However, in binary calculation, 1 + 1 = 10; for binary number 100, take the inverse, equal to 001, not - 100. p(ctx, [dirty]) { // one of 3 sections ... if (dirty & /*$user*/ 1 && // conditional Part I t5_value !== (t5_value = /*$user*/ ctx[0].name + "")) { // conditional Part II set_data(t5, t5_value); // the payload - update the DOM! } ... snip snip }, //The set_data() function is an svelte helper that actually updates the DOM function set_data(text, data) { data = '' + data; if (text.data !== data) text.data = data; }
a key
● the ctx [] array contains all our dependencies. ctx[0] happens to be ours
u
s
e
r
yes
as
(
through
too
notes
Buddhism
can
with
see
Out
)
●
d
i
r
t
y
in
package
contain
I
Guys
place
have
change
amount
"
Chen
used
"
of
Press
position
tired
plus
(
each
individual
because
change
amount
one
position
)
●
strip
piece
of
The first
one
Department
branch
yes
PULL
Out
user object (as can be seen from the comments) ● dirty contains the bitwise accumulation of all our variables "stale" (one bit for each dependent variable) ● the first part of the condition is pull-out
User object (as can be seen from the comments) ● dirty contains the bitwise accumulation of all our variables "stale" (one bit for each dependent variable) ● the first part of the condition is to pull out the dirty flag of the user dependent variable (using the bit wise and operator - &]). If so, we will continue with the second part (via the logical and operator - &&)
● the second conditional part is actually to do two things: compare the latest ts_value from our HTML code segment (after converting it to string + '') with the output of the previous / next judgment (using identification semantics! = =). Only when the previous / next change occurs, will he execute conditional payload (dom update) The final condition is a very simple raw string comparison,
Personal understanding: the internal mechanism of the object added to the reaction when the attribute is updated is the mechanism to filter the updated content through p, that is, the update function. The method will store all our dependencies through the ctx [] array, such as KAtex parse error: expected 'EOF', got '&' at position 60:... The process is to first see whether there is a direct bit& ̲// Finally, the value of user 1 is the key point. If you look at the content in html, that is, t5_value=/$user/ ctx[0].name + "", whether ts_value is the same as the latest content, and if it is different, update the dom.
Pre analytical change
html completion starts with "1 -"
<i class:long-distance={phone.startsWith('1-')}> ... snip snip </i>
The problem here is that svelte will re execute HTML snippet according to whether the dependency is changed or not, regardless of whether the css class is changed or not. Here, we only change the second half and keep the first half, which leads to a higher number of reflection counts
Solution
Moving logical conditions into code snippets and generating html snippets will result in less execution
//Some codes are as follows $: classes = phone.startsWith('1-') ? 'long-distance' : ''; <i class="{probe2.monitor() || classes}"> {probe3.monitor() || phone} </i>?
Optimization considerations
Here are the following "extra" considerations for optimization
Insight: optimization is relevant only when the active ingredient reacts
● the initial rendering of a component (when installed) will unconditionally execute all its html fragments (regardless of dependencies or conditions)
● if there is no reactivity thereafter, there is no need to focus on these optimization techniques
● note, however, that reactivity is difficult to predict. In addition, future revisions to your code may introduce reactivity. So be careful!