<tempalte>
<div>{{person1}}--{{person2}}</div>
<!-- { name: 'Amy'} and {name: 'Tom'}, and after three seconds person1 becomes {name: 'Tony'} -->
</template>
<script>
import { ref, reactive } from 'vue';
export default {
setup () {
const person1 = ref({ name: 'Amy' });
const person2 = reactive({ name: 'Tom' });
setTimeout(() = > {
person1.value = {name: 'Tony'};
person2 = {name: 'Tony'};
}, 3000);
return{ person1, person2 }; }};</script>
Copy the code
This results in a reversal of my understanding of ref and Reactive, which are not distinguished by data being base types or reference types.
ref
A Proxy that takes an any parameter and returns a {value:} package can change the value attribute to make a responsive assignment, but accessing the internal structure in the setup scope also requires the value attribute, which automatically unwraps the value package in the template.
Usage Scenario: Applicable to data that requires assignment, basic type (required), and reference type with shallow structure (recommended).
reactive
Accepts a parameter of a reference type and returns its Proxy, unable to respond to an assignment to the entire Proxy. Processing of reference types by REF is handled by Reactive after wrapping value. As a result, Reactive includes a responsive base API on the website.
Usage scenarios: Data that does not require assignment operations, and reference types with deeper structures (recommended).
<tempalte>
<div>{{person1 === person2}}</div><! --true -->
</template>
<script>
import { ref, reactive } from 'vue';
export default {
setup () {
let obj = { name: 'Amy' };
const person1 = ref(obj);
const person2 = reactive(obj);
console.log(person1.value === person2); // true
return{ person1, person2 }; }};</script>
Copy the code
In the processing of reference types, the difference between the two is the package in which ref has value, and the inner part is the same.
Related applications
v-model
<tempalte>
<my-component v-model="data"></my-component>
<! -- equivalent to -->
<my-component
modelValue="data"
@update:modelValue="e => data.value=e"></my-component>
</template>
Copy the code
The V-Model has implicit assignment operations, so the PROPS of the V-Model also need to pass in the data processed by the REF, not reactive.
ref Element
Setup is executed before mount, so how do we get the REF bound DOM from there?
<tempalte>
<div ref="div"></div>
</template>
<script>
import { ref, onMounted } from 'vue';
export default {
setup () {
const div = ref(null);
onMounted(() = > {
console.log(div.value); // <div></div>
});
return{ div }; }};</script>
Copy the code
Ref generates a null-wrapped Proxy and binds the DOM with the exposed attribute name as the name of the REF to obtain the DOM.