The setup function

When you use the setup function, it takes two arguments: props, context

The component instance has not yet been created because setup on beforeCreate is executed. Therefore, you can only access the following properties: props, attrs, slots, emit

props

The first argument to the setup function is props, which is the value passed by the parent component to the child component, but only if it has that property defined in props.

context

The second argument passed to the setup function is context. Context is a plain JavaScript object that exposes three component properties: attrs, slots, and emit

 setup(props, context) { // Or just deconstruct the context here
   // Attribute (non-responsive object)
   console.log(context.attrs) // If an attribute is not defined in props, it is an attribute in attrs; But Vue suggested that it would be better if all properties were defined in props

   // slot (non-responsive object)
   console.log(context.slots)

   // Trigger event (method)
   console.log(context.emit)
 }
Copy the code

The life cycle

Option type API Hook inside setup
beforeCreate Not needed*
created Not needed*
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered

Because setup runs around beforeCreate and Created lifecycle hooks, there is no need to explicitly define them. In other words, any code written in these hooks should be written directly in the Setup function.

import { onMounted } from 'vue';
export default {
 setup() {
   // mounted
   	onMounted(() = > {
     		console.log('Component is mounted! ')})}Copy the code

Responsiveness base API

Reactive – Reactive complex data *

Returns a responsive copy of the object; Reactive transformation is “deep” — it affects all nested properties. In an ES2015 Proxy-based implementation, the returned Proxy is not equal to the original object. You are advised to use only reactive proxies to avoid relying on raw objects.

const obj = reactive({ count: 0 })
Copy the code
const count = ref(1)
const obj = reactive({ count })// ref will not be deconstructed
// const obj = reactive({}) 
// obj.count = count// Important: when a ref is assigned to a Reactive property, the ref is automatically deconstructed.
// There is no difference between the two
console.log(obj.count === count.value) // true

count.value++ // It will update 'obj.value'
console.log(count.value) / / 2
console.log(obj.count) / / 2

// It also updates' count 'ref
obj.count++
console.log(obj.count) / / 3
console.log(count.value) / / 3
Copy the code

ToRaw – Returns the original object *

Returns the original object of the Reactive or Readonly agent. It can be used to read data temporarily without the overhead of proxy access/trace, or to write data without triggering changes. It is not recommended to preserve persistent references to the original object. Use with caution.

Application scenario: Return an Object object instead of a proxy object that can be manipulated without triggering page changes.

MarkRaw – Adds markup for unresponsive data

Marks an object so that it will never be converted to a proxy. Returns the object itself.

Note: Only the root level of an object can be marked. If you add a nested, unmarked original object to a reactive object and then access that reactive object again, you will get the proxied version of the original object. This can lead to an identity risk — that is, performing an operation that depends on the object itself but uses both the original and the proxied version of the same object:

const foo = markRaw({
  nested: {}})const bar = reactive({
  // Although 'foo' is marked original, foo.nested is not.
  nested: foo.nested
})
console.log(foo.nested === bar.nested) // false
Copy the code

ShallowReactive – Shallow, reactive data objects

Create a reactive proxy that tracks the responsiveness of its own property, but does not perform deep reactive transformations of nested objects (exposing raw values). Unlike Reactive, shallowReactive only listens to root-level attributes, and views do not change when secondary or higher attributes are updated.

const state = shallowReactive({
  foo: 1.nested: {
    bar: 2}})// Changing the nature of state itself is reactive
state.foo++
/ /... But nested objects are not converted
isReactive(state.nested) // false
state.nested.bar++ // non-responsive
Copy the code

Ref-responsive simple data *

Takes an internal value and returns a reactive and mutable REF object. The ref object has a single property.value pointing to an internal value.

Unlike Reactive, which is used to listen to complex data, ref is usually used to listen to simple data;

const count = ref(0)
Copy the code

ToRef – Creates a connection for a property of a reactive object

Can be used to create a new REF for a property on a source responsive object. The REF can then be passed, maintaining a reactive connection to its source property. That is, the view layer will be updated even if it is deconstructed and still retains its connection to the previous object;

const state = reactive({
 foo: 1.bar: 2
})
const fooRef = toRef(state, 'foo')
fooRef.value++
console.log(state.foo) / / 2
state.foo++
console.log(fooRef.value) / / 3
Copy the code

ToRefs – Creates connections * for all properties of a reactive object

Converts a reactive object to a normal object, where each property of the resulting object is a REF pointing to the corresponding property of the original object.

const state = reactive({
  foo: 1.bar: 2
})
const stateAsRefs = toRefs(state)
// the ref and the original property are "linked"
state.foo++
console.log(stateAsRefs.foo.value) / / 2
stateAsRefs.foo.value++
console.log(state.foo) / / 3
Copy the code

ToRefs is useful when returning a reactive object from a synthesized function so that the consuming component can decompose/diffuse the returned object without losing responsiveness:

function useFeatureX() {
  	const state = reactive({
    		foo: 1.bar: 2
  	})
  	// do something // convert to ref on return
  	return toRefs(state)
}
export default {
  	setup() {
    	// Can be destructed without losing responsiveness
    	const { foo, bar } = useFeatureX()
    		return {
      			foo,
      			bar
    		}
  	}
}
Copy the code

ShallowRef – creates a shallowRef

Create a ref that tracks changes in its.value, but doesn’t make its value reactive as well.

const foo = shallowRef({}) // Changing the value of ref is reactive
foo.value = {} // But this value will not be converted.
isReactive(foo.value) // false
Copy the code

TriggerRef – Updates the deep ref view

Manually perform any side effects associated with shallowRef

const shallow = shallowRef({
  greet: 'Hello, world'
})

// This does not trigger side effects because refs are shallow
shallow.value.greet = 'Hello, universe'

// record "Hello, universe"
triggerRef(shallow)
Copy the code

Watch and computed *

Watch (value,key=>{}); To monitor reactive, use watch(()=>value,key=>{}). The first parameter is the listening object, with the array can listen to multiple parameters, the second parameter is the operation that needs to be carried out when dynamic changes, the third parameter is whether to choose deep listening, listen immediately.

WatchEffect: A function is placed directly inside the watchEffect, which is executed whenever a value is updated, similar to calculating a property.

Computed: Need to receive with a variable

const state = reactive({count: 1})
const value = computed(() = > state.count + 1); // value(ref) : 2
watchEffect(() = > {
  console.log('listening state. The count',state.count);
  // This function is re-executed whenever the watchEffect internal dependent variable is changed
})
const watchVal = watch(() = > state.count,(key) = >{console.log(key)})
watchVal(); // When watchVal is executed, the state. Count function is no longer listened on
Copy the code