The setup function and lifecycle changes
The setup
Function and Lifecycle Changes
Vue 3 introduces the Composition API, with the setup
function being its core component. It replaces most of the Options API from Vue 2, including data
, methods
, computed
, and others, while also redesigning the lifecycle hooks. The setup
function executes before the component instance is created, meaning it cannot access this
. Instead, it exposes data and functions through parameters and return values.
Basic Usage of the setup
Function
The setup
function takes two parameters: props
and context
. props
contains the component's properties, while context
provides utilities like attrs
, slots
, and emit
.
<script>
import { ref } from 'vue';
export default {
props: {
message: String
},
setup(props, context) {
const count = ref(0);
const increment = () => {
count.value++;
};
// Expose to template
return {
count,
increment,
context
};
}
};
</script>
In this example, props
includes the message
property passed from the parent component, and context
can be used to access slots or emit events. ref
creates reactive data, and increment
is a method—both are exposed to the template via return
.
Changes in Lifecycle Hooks
Vue 3's lifecycle hooks differ from Vue 2's, with most hooks accessible via functions within the setup
function. Below is a comparison between Vue 2 and Vue 3 lifecycle hooks:
Vue 2 Lifecycle Hook | Vue 3 Equivalent in setup |
---|---|
beforeCreate |
No direct equivalent; setup runs before beforeCreate |
created |
No direct equivalent; setup runs before created |
beforeMount |
onBeforeMount |
mounted |
onMounted |
beforeUpdate |
onBeforeUpdate |
updated |
onUpdated |
beforeDestroy |
onBeforeUnmount |
destroyed |
onUnmounted |
activated |
onActivated |
deactivated |
onDeactivated |
Using Lifecycle Hooks in setup
Within the setup
function, lifecycle hooks are used by importing functions from the vue
package. These hooks accept a callback that executes when the corresponding lifecycle stage is triggered.
<script>
import { onMounted, onUpdated, onUnmounted } from 'vue';
export default {
setup() {
onMounted(() => {
console.log('Component mounted');
});
onUpdated(() => {
console.log('Component updated');
});
onUnmounted(() => {
console.log('Component unmounted');
});
}
};
</script>
Asynchronous Operations in setup
The setup
function can be asynchronous, which is useful for fetching data from APIs. This can be achieved using async/await
or by returning a Promise.
<script>
import { ref } from 'vue';
export default {
async setup() {
const data = ref(null);
const response = await fetch('https://api.example.com/data');
data.value = await response.json();
return {
data
};
}
};
</script>
Comparison with Vue 2 Lifecycle
In Vue 2, lifecycle hooks are defined directly as component options, whereas in Vue 3, they are registered via function calls within the setup
function. This design centralizes logic, especially for complex components.
Vue 2 Example:
<script>
export default {
data() {
return {
count: 0
};
},
mounted() {
console.log('Component mounted');
},
beforeDestroy() {
console.log('Component about to be destroyed');
}
};
</script>
Vue 3 Example:
<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
export default {
setup() {
const count = ref(0);
onMounted(() => {
console.log('Component mounted');
});
onBeforeUnmount(() => {
console.log('Component about to be destroyed');
});
return {
count
};
}
};
</script>
Advantages of the Composition API
The setup
function and Composition API make code easier to organize and reuse. Logic can be grouped by feature rather than scattered across different lifecycle hooks. For example, data fetching and event handling can be encapsulated in a separate function and then called within setup
.
<script>
import { ref, onMounted } from 'vue';
function useCounter() {
const count = ref(0);
const increment = () => {
count.value++;
};
onMounted(() => {
console.log('Counter initialized');
});
return {
count,
increment
};
}
export default {
setup() {
const { count, increment } = useCounter();
return {
count,
increment
};
}
};
</script>
Common Issues and Considerations
this
is unavailable: Insidesetup
,this
isundefined
. All data and functions must be exposed to the template viareturn
.- Reactive data: Use
ref
orreactive
to create reactive data. Returning plain objects will not make them reactive. - Lifecycle hook execution order: Hooks in
setup
execute in the order they are registered but still follow Vue’s overall lifecycle flow. - Async
setup
: Ifsetup
is async, ensure the parent component usesSuspense
or handles the async state properly.
Integration with Other APIs
The setup
function works seamlessly with other Vue features like provide/inject
, watch
, and computed
.
<script>
import { provide, ref, watch, computed } from 'vue';
export default {
setup() {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
provide('count', count);
watch(count, (newValue, oldValue) => {
console.log(`count changed from ${oldValue} to ${newValue}`);
});
return {
count,
doubleCount
};
}
};
</script>
Performance Optimization
Within setup
, you can use shallowRef
or shallowReactive
to reduce reactivity overhead, especially when dealing with large objects or arrays.
<script>
import { shallowRef } from 'vue';
export default {
setup() {
const largeList = shallowRef([]);
// Manually trigger updates
const updateList = (newList) => {
largeList.value = newList;
};
return {
largeList,
updateList
};
}
};
</script>
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn