The core usage of Composition API in Vue3
What is Composition API?
Composition API is also called combined API, which is Vue3. New features in x. By creating Vue components, we can extract the repeatable parts of the interface into reusable code segments. Before the Composition API, Vue-related business code needed to be configured to a specific area of the option. If this approach is used in a large project, it will cause problems later. The maintenance is relatively complicated, and the code reusability is not high. Vue3's Composition API solves this problem.
Use ref and reactive to define responsive data in setup
Before using ref and reactive to define data, you need to deconstruct it from vue.
import {ref,reactive} from 'vue';
Both ref and reactive can define responsive data. The defined data can be obtained directly in the Vue template. However, if it is obtained through methods, there are certain differences in the acquisition of data defined by ref and reactive. ref The defined data needs to be obtained indirectly through the value attribute, and the data defined by reactive can be obtained directly. The same is true when modifying these two types of data.
export default { setup() { // 使用ref定义响应式数据 const title = ref("这是一个标题"); // 使用reactive定义响应式数据 const userinfo = reactive({ username: "张三", age: 20 }); // 获取reactive中的属性可以直接获取 const getUserName = () => { alert(userinfo.username) }; // 获取ref中的数据需要通过value属性 const getTitle = () => { alert(title.value) }; const setUserName = () => { // 修改reactive中的属性可以直接修改 userinfo.username = "修改后的张三" }; const setTitle = () => { // 修改ref中的属性,需要通过value title.value = "这是修改后的标题" }; return { title, userinfo, getUserName, getTitle, setTitle, setUserName } }, data() { return { msg: "这是Home组件的msg" } }, methods: { run() { alert('这是Home组件的run方法') } } }
You can use v-model to directly perform two-way data binding.
<input type="text" v-model="title"> <input type="text" v-model="userinfo.username">
toRefs deconstructs responsive object data
The reason why toRefs is needed is because the data deconstructed through toRefs also has responsive characteristics and is processed through traditional expansion operators. Destructuring does not have the characteristics of responsiveness, which is why toRefs is needed.
Deconstruct toRefs from vue
import {ref,reactive,toRefs} from 'vue';
Make the following modifications in the return data of setup
return { title, userinfo, getUserName, getTitle, setTitle, setUserName, ...toRefs(article) }
Computed attributes in setup
The calculated properties in setup are similar to general calculated properties. The difference is that this cannot be read.
setup() { let userinfo = reactive({ firstName: "", lastName: "" }); let fullName = computed(() => { return userinfo.firstName + " " + userinfo.lastName }) return { ...toRefs(userinfo), fullName } }
readonly: Deep read-only proxy
The meaning of readonly is to be able to convert responsive objects into ordinary primitive objects.
Introducing readonly.
import {computed, reactive,toRefs,readonly} from 'vue'
Pass in the responsive object to readonly.
let userinfo = reactive({ firstName: "666", lastName: "" }); userinfo = readonly(userinfo);
watchEffect in setup
watchEffect in setup has the following characteristics.
Can monitor data changes in the setup. Once the data changes, the callback function in watchEffect will be executed.
The data in the setup will not change in real time, and it will be executed once initially.
setup() { let data = reactive({ num: 1 }); watchEffect(() => { console.log(`num2=${data.num}`); }); setInterval(() => { data.num++; },1000) return { ...toRefs(data) } }
watch in setup
The basic method of using watch to monitor data.
setup() { let keyword = ref("111"); watch(keyword,(newData,oldData) => { console.log("newData是:",newData); console.log("oldData是:",oldData); }) return { keyword } }
The difference between watch and watchEffect
watch will not be executed when the page is rendered for the first time, but watchEffect will.
watch can obtain the values before and after the data status changes.
Life cycle hook function in setup
The life cycle hook in setup is similar to calling a function directly.
setup() { let keyword = ref("111"); watch(keyword,(newData,oldData) => { console.log("newData是:",newData); console.log("oldData是:",oldData); }) onMounted(() => { console.log('onMounted'); }) onUpdated(() => { console.log('onUpdated'); }) return { keyword } }
Props in setup
The parent component passes the value.
<Search :msg="msg" />
StatementReceive
props: ['msg'], setup(props) { console.log(props); }
Provide and inject
Sometimes, we need to pass data from parent component to child component, but if the parent component to Subcomponent is a deeply nested relationship, and passing it through props will become troublesome. In this case, we can use provide and inject to achieve it.
General usage
The root component passes data through provide.
export default { data() { return { } }, components: { Home }, provide() { return { title: "app组件里面的标题" } } }
Components that need to receive data receive it through the inject statement.
export default { inject: ['title'], data() { return { } }, components: { } }
After the statement is received, it can be used directly.
<template> <div class="container"> 这是Location组件 {{title}} </div> </template>
provide can obtain the data in this
export default { data() { return { title: "根组件的数据" } }, components: { Home }, provide() { return { title: this.title } } }
Note: In the above general usage, if the data in the parent component occurs Changes in sub-components will not change, so it is recommended to use provide and inject in the composition API below to achieve synchronous changes.
provide and inject in setup
Root component
import Home from './components/Home.vue' import {ref,provide} from 'vue' export default { setup() { let title = ref('app根组件里面的title'); let setTitle = () => { title.value = "改变后的title" } provide("title",title); return { title, setTitle } }, data() { return { } }, components: { Home } }
Components that use data
import {inject} from 'vue' export default { setup() { let title = inject('title'); return { title } }, data() { return { } }, components: { } }
The difference from props is , the data in the child component will be synchronized to the parent component if two-way data binding is used.
Recommended learning: "The latest 5 vue.js video tutorial selections"
The above is the detailed content of Introducing the Composition API and its core usage in Vue3. For more information, please follow other related articles on the PHP Chinese website!