In daily useVue
When developing a project, calculate attributescomputed
It is a very commonly used feature. Its main function is to process the data and then return new data, so that there is no need to write too much logical code in the template, making the template more concise and readable.
Today I'll share some of the things I'm usingVue
ofcomputed
I hope some tips when calculating attributes can help everyone.
1. Basic usage of calculating attributes
The usage of calculating attributes is very simple, and they are divided into four parts:getter
、setter
、onTrack
、onTrigger
。
-
get
: Computing attributesgetter
Function, when the dependence of the calculated attribute changes, the function will be executed and the value of the calculated attribute will be returned. -
set
: Computing attributessetter
Function, when the value of the calculated attribute is directly modified, the function will be executed. -
onTrack
: This function will be executed when the dependency of a calculated attribute is tracked. -
onTrigger
: This function is executed when the dependencies of the computed attribute change.
The code is as follows:
import { computed } from 'vue' const count = ref(0) const plusOne = computed({ get() { return + 1 }, set(val) { = val - 1 }, onTrack(e) { debugger; }, onTrigger(e) { debugger; } }); () // 1 () // 0 = 1 () // 2 () // 1
The most common thing we use here isget
, can be abbreviated as follows:
const plusOne = computed(() => + 1)
onTrack
andonTrigger
Generally used for debugging, when we want to know what changes have occurred in the dependencies of computed properties, we can break the debugging point in these two functions.
For details, please refer to the official website:
- Calculate properties
- Computational attribute debugging
The official website gives some usage scenarios for computing attributes and some precautions for computing attributes. If you are placing some of them here, you can take a look. Let me share some tips when using computing attributes.
2. Tips for calculating attributes
2.1. Listen to changes in multiple data
// Multiple data want to be monitored at the same timeconst a = ref(1) const b = ref(2) const c = ref(3) // Merge it into a computed propertyconst multiply = computed(() => { return { a: , b: , c: , } }) // Listen to the changes in the calculation propertieswatch( () => , (val) => { (val) } ) // Modify data = 2 // { a: 2, b: 2, c: 3 } = 3 // { a: 2, b: 3, c: 3 } = 4 // { a: 2, b: 3, c: 4 }
2.2. Partial properties of the listening object
const obj1 = ref({ a: 1, b: 2, c: 3, }) const obj2 = ref({ a: 1, b: 2, c: 3, }) // Some properties of the listening objectconst combine = computed(() => { return { a: , b: , } }) // Listen to the changes in the calculation propertieswatch( () => , (val) => { (val) } ) // Modify data = 2 // { a: 2, b: 2 } = 3 // No output = 4 // No output = 2 // No output = 3 // { a: 2, b: 3 } = 4 // No output
Multiple objects can be combined to listen for changes in some fields, so there is no need to manually determine which field of which object is specifically modified.
2.3. Listen to some elements of the array
const arr1 = ref([1, 2, 3]) const arr2 = ref([1, 2, 3]) // Listen to some elements of the arrayconst combine = computed(() => { return [ [0], [1], ] }) // Listen to the changes in the calculation propertieswatch( () => , (val) => { (val) } ) // Modify data[0] = 2 // [2, 2] [1] = 3 // No output[2] = 4 // No output[0] = 2 // No output[1] = 3 // [2, 3] [2] = 4 // No output
You can also listen to changes in some elements like objects for arrays.
2.4. Cache and update
// This is a big object, I don't need it to be responsive, but I need it to be responsively updatedconst list = new Array(100).fill(0).map((item, index) => ({key: index, value: item})) // Force refreshconst forceFlush = ref(0); const cache = computed(() => { ; // Use it here, just do nothing // Here we will perform a series of calculations on large objects, and then cache the results for easy use const cache = ((prev, curr) => { prev[] = curr; return prev }, {}) // It is convenient to obtain directly through key return (key) => { return cache[key] || {} } }) ((0).value); // 0 // It will not be updated herelist[0] = {key: 0, value: 1}; ((0).value); // 0 // Just give a refresh signal++; ((0).value); // 1
2.5. Two-way binding
const props = defineProps({ modelValue: { type: String, default: "" } }); const emit = defineEmits(["update:modelValue"]); const value = computed({ get() { return ; }, set(val) { emit("update:modelValue", val); } }); = 'hello';
Two-way binding requires cooperationdefineEmits(["update:modelValue"])
Use each callemit("update:modelValue", val)
Very troublesome;
Use nowcomputed
It can be achieved = value
This method is directly modified, which is very intuitive and satisfies the principle of one-way data flow;
Summarize
In daily useVue
In, use reasonablyVue
The various features of this not only double the development efficiency, but also make the code look cleaner.
Be careful that you can use various features, but don’t show off your skills. Just be easy to use. Don’t write codes that no one can shake your status and manually do the dog head.
The above is a detailed analysis of how Vue skillfully uses computed to calculate attributes. For more information about Vue computed, please follow my other related articles!