Home > Web Front-end > Vue.js > Introducing the Composition API and its core usage in Vue3

Introducing the Composition API and its core usage in Vue3

藏色散人
Release: 2021-12-10 15:04:56
forward
2491 people have browsed it

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';
Copy after login

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方法')
    }
  }
}
Copy after login

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">
Copy after login

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 &#39;vue&#39;;
Copy after login

Make the following modifications in the return data of setup

return {
  title,
  userinfo,
  getUserName,
  getTitle,
  setTitle,
  setUserName,
  ...toRefs(article)
}
Copy after login

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
    }
  }
Copy after login

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 &#39;vue&#39;
Copy after login

Pass in the responsive object to readonly.

let userinfo = reactive({
  firstName: "666",
  lastName: ""
});
userinfo = readonly(userinfo);
Copy after login

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)
    }
  }
Copy after login

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
    }
  }
Copy after login

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

Introducing the Composition API and its core usage in Vue3

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(&#39;onMounted&#39;);
    })
    onUpdated(() => {
      console.log(&#39;onUpdated&#39;);
    })
    return {
      keyword
    }
  }
Copy after login

Props in setup

The parent component passes the value.

<Search :msg="msg" />
Copy after login

StatementReceive

props: [&#39;msg&#39;],
  setup(props) {
    console.log(props);
  }
Copy after login

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组件里面的标题"
    }
  }
}
Copy after login

Components that need to receive data receive it through the inject statement.

export default {
  inject: [&#39;title&#39;],
  data() {
    return {
    }
  },
  components: {
  }
}
Copy after login

After the statement is received, it can be used directly.

<template>
  <div class="container">
    这是Location组件
    {{title}}
  </div>
</template>
Copy after login
  • provide can obtain the data in this

export default {
  data() {
    return {
      title: "根组件的数据"
    }
  },
  components: {
    Home
  },
  provide() {
    return {
      title: this.title
    }
  }
}
Copy after login

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 &#39;./components/Home.vue&#39;
import {ref,provide} from &#39;vue&#39;
export default {
  setup() {
    let title = ref(&#39;app根组件里面的title&#39;);
    let setTitle = () => {
      title.value = "改变后的title"
    }
    provide("title",title);
    return {
      title,
      setTitle
    }
  },
  data() {
    return {
    }
  },
  components: {
    Home
  }
}
Copy after login

Components that use data

import {inject} from &#39;vue&#39;
export default {
  setup() {
    let title = inject(&#39;title&#39;);
    return {
      title
    }
  },
  data() {
    return {
    }
  },
  components: {
  }
}
Copy after login

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!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template