1.Data Property
The component’s data option is a function. Vue calls this function during the creation of new component instances. It should return an object that Vue wraps through a responsive system and stores in the component instance as $data. For convenience, any top-level properties of the object are also exposed directly through the component instance.
- Instance properties are only added when the instance is first created, so you need to make sure they are in the object returned by the data function
- If necessary, use null, undefined, or other placeholder values for properties that have not yet provided the required value
- It is possible to add a new property directly to the component instance that is not included in data, but because the property is not in the underlying responsive $data object, the Vue’s responsive system does not automatically track it
- Vue uses the $prefix to expose its built-in API through component instances. It also reserves the _ prefix for internal properties, and top-level data property names starting with these two characters should be avoided
Method 2.
We use the Methods option to add methods to the component instance, which should be an object containing the required methods.
- Vue automatically binds methods to this so that it always points to the component instance. This ensures that methods retain the correct this pointer when used as event listeners or callbacks. Arrow functions should be avoided when defining methods, as this prevents Vue from binding proper this pointer
- Methods, like all other properties of a component instance, can be accessed in the component’s template, where they are typically used as event listeners
- It is also possible to call methods directly from the template, and it is usually better to use ‘computed properties’ instead, but in cases where computed properties are not feasible, using’ methods’ can be useful
- Methods called from templates should not have any side effects, such as changing data or triggering asynchronous processes, and should instead have lifecycle hooks if they want to do anything else
3. Anti-shake and throttle
Vue does not have built-in support for anti-shake and throttling, but libraries such as Lodash can be used to do so.
- If a component is only used once, you can apply defak directly to Methods, but this approach is potentially problematic for reusable components because they all share the same defak function. To make component instances independent of each other, you can add the defak function to the lifecycle hook created