Global mixins
Global mixing will affect every component
// main.js
const app = createApp(App);
app.mixin({
data() {
return {
globalMsg: 'This is a global mixed message'}}})Copy the code
extend
- Similar mixins
Multiple components rely on the same method as follows:
import CommonComponent from './common/CommonComponent.vue';
export default {
extends: CommonComponent // You can then use the properties in the CommonComponent (which feel exactly like mixins)
}
Copy the code
- In order to execute opintionApi, run props -> method -> data -> computed -> watch
setup
Note:
- Setup does not bind this
- If a property defined in CompositionApi (SETUP) conflicts with a property defined in OptionApi, the property defined in CompositionApi is preferred. (The actual operation is optionApi.)
setup(props, ctx) {
// CTX common attributes
const {
slots, / / slots
attrs, // Non-props attribute mounted on the element
emit / / event
} = ctx;
}
Copy the code
Responsive data
import{... }from 'vue';
Copy the code
– ref
– reactive
– isProxy
– isRef
Check whether the variable was created by ref, Boolean
– readonly
To determine whether variable by reactive | readonly created Boolean
– isReactive
Check whether variables are created by Reactive, Boolean
(If the variable is readonly wrapped around reactive, it still returns true)
– toRaw
Return the raw object of the Reactive or Readonly agent (use with caution)
– toRefs(common)
Objects passed in to the deconstruction must be reactive objects
After deconstructing reactive data, the deconstructed data is still reactive data (convert all properties of reactive objects to refs and establish connections).
const {
name,
age
} = toRefs(reactive({name: 'cqc'.age: 24}))
Value = newValue to follow the newValue
Copy the code
– toRef
Same as toRefs, but only one of the attributes is converted
const info = reactive({
age: 25
})
const age = toRef(info, age)
Copy the code
– shallowReactive
Create a responsive proxy data (shallow, listening only to the first layer)
– shallowRef
Create a reactive proxy data (shallow, listening only to the first layer), and then use triggerRef() if you want to refresh the screen at some point,
TriggerRef accepts a ref type and refreshes the screen every time it is called
– triggerRef
Refresh the view for shallowRef, performing all side effects associated with shallowRef (dependencies)
– shallowReadonly
Create a reactive proxy data whose first layer is read-only (the deeper layer is still read-write)
– unref
Unpack variables of type REF
Gets the value in a ref reference, returning the internal value if the argument is a ref, or itself otherwise
val = isRef(val) ? val.value : val;
Copy the code
import {
ref, // Pass in the base variable type
reactive, // Pass in the reference variable type
readonly
} from 'vue';
Copy the code
ref
Use ref in the template and VUE will unpack it automatically (automatically add ref. Value)
// Shallow unpack
const counter = ref(100);
const info = {
counter
} // Unless you package info reactive, it is shallow unpacking
Copy the code
It’s inside template
<! -- Need to write it down in full (no automatic unpacking) -->
{{info.counter.value}}
Copy the code
reactive
Gets reactive data of the reference type
readonly
This is a new Proxy that hijacks the set method
customRef
It is generally used in component libraries. To create a custom ref (which can freely control track and trigger), it needs to be used together with the factory function, which accepts two parameters (track, trigger).
Track: tracking depends on calling track() on get; Trigger: Trigger () is called when the update view is set;
- The customRef function returns an object with set and get methods
- Example: Here is an anti-shake example
const useDebounce(value, delay) { let timer = null; return customRef((track, trigger) = > { return { get() { track(); // Collect dependencies return value }, set(newValue) { value = newValue; timer && clearTimeout(timer); timer = setTimeout(() = > { trigger(); // Update the view }, delay) return true; }}})}setup() { return { text: useDebounce('There's a 500 millisecond delay.'.500)}}Copy the code
computed
A computed function takes a parameter that can take two forms
1. An object with get and set functions. 2
example:
const state = ref('cqc');
const computedTest = computed(() = > state.value + 'computed');
const computedTest2 = computed({
get() {
return state.value + 'computed'
},
set(newValue) {
state.value = newValue;
return true; }})Copy the code
Listen to the data
Vue3 provides two listening apis
API | instructions |
---|---|
watch | Listen for changes in the data and perform some actions |
watchEffect | It is executed immediately at the beginning, collecting all of the responsive object data in it, and executing it once the data has changed |
Watch the instance
const name = ref('cqc');
const state = reactive({
name: 'cqc'.fav: 'play-game'.data: {
io: '/td'}})// Watch distinguishes between listening for two types of responsive data
// 1. The type of the original value being listened on is normal
watch(name, (newValue, oldValue) = > {
console.log(newValue, oldValue);
})
// 2. The original value type being listened on is a reference type
watch(() = >({... state}),(newValue, oldValue) = > {
// If state has reference data attributes, then the attributes in newValue, oldValue, still refer to themselves, that is, the newValue of the reference data is equal to the oldValue
console.log(newValue, oldValue);
})
//-------------
// Listen for a single attribute
watch(() = > state.name, (newValue, oldValue) = > {
console.log(newValue, oldValue);
})
// Listen to multiple data sources
watch(
[name, () = > ({ ...state })],
(newValue, oldVAlue) = > {
// newValue, oldValue will also be an array with subscripts corresponding to the data source that was passed in[newName, newState] = newValue; [oldName, oldState] = oldValue; })// The third parameter of the watch configuration item
watch(
() = > ({ ...state }),
(newValue, oldValue) = > {},
{
deep: false.// Whether to deep monitor
immediate: false // Execute immediately (execute immediately when initializing)})Copy the code
WatchEffect instances can be configured to execute watchEffect immediately. WatchEffect instances must execute watchEffect immediately upon initialization.
const state = reactive({
name: 'cqc'
})
const watchEffectStop = watchEffect(
// watchEffect is the first parameter
(onInvalidate) = > {
// onInvalidate will execute the callback when the side effect is about to execute or the listener is stopped
onInvalidate(() = > {
// Can do some cleaning here
})
// watchEffect starts once by default (collect reactive data inside, execute once collected data starts to change)
console.log('watchEffect', state.name);
},
// watchEffect second argument
{
flush: 'pre'
Pre post sync - pre: the default value is executed before DOM update. -post: the default value is executed after DOM update. -sync Forcibly synchronizes data (not recommended) */})if(someFlag) {
// Manually stop watchEffect listening
watchEffectStop();
}
Copy the code
Access to components | element instance
Equivalent to this.$refs.xxx in vue2. X
<Component-A ref="ComponentA" />
Copy the code
setup() {
// ComponentA. Value is automatically assigned by vUE after the component is updated
const ComponentA = ref(null);
return {
ComponentA
}
}
Copy the code
getCurrentInstance
It is primarily used to access the current component instance in the Position API
// main.js
For example, I now add a property to the global app configuration
app.config.globalProperties.$name = 'cqc';
// other place
setup() {
const instanceNow = getCurrentInstance();
const globalConfig = instanceNow.appContext.config.globalProperties;
globalConfig.$name; // cqc
}
Copy the code