search
HomeWeb Front-endVue.jsIntroducing the Composition API and its core usage in Vue3

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

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

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

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
    }
  }

Props in setup

The parent component passes the value.

<Search :msg="msg" />

StatementReceive

props: [&#39;msg&#39;],
  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: [&#39;title&#39;],
  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 &#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
  }
}

Components that use data

import {inject} from &#39;vue&#39;
export default {
  setup() {
    let title = inject(&#39;title&#39;);
    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!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
分享两个可以绘制 Flowable 流程图的Vue前端库分享两个可以绘制 Flowable 流程图的Vue前端库Sep 07, 2022 pm 07:59 PM

前端有没有现成的库,可以直接用来绘制 Flowable 流程图的?下面本篇文章就跟小伙伴们介绍一下这两个可以绘制 Flowable 流程图的前端库。

vue是前端css框架吗vue是前端css框架吗Aug 26, 2022 pm 07:37 PM

vue不是前端css框架,而是前端JavaScript框架。Vue是一套用于构建用户界面的渐进式JS框架,是基于MVVM设计模式的前端框架,且专注于View层。Vue.js的优点:1、体积小;2、基于虚拟DOM,有更高的运行效率;3、双向数据绑定,让开发者不用再去操作DOM对象,把更多的精力投入到业务逻辑上;4、生态丰富、学习成本低。

聊聊Vue3+qrcodejs如何生成二维码并添加文字描述聊聊Vue3+qrcodejs如何生成二维码并添加文字描述Aug 02, 2022 pm 09:19 PM

Vue3如何更好地使用qrcodejs生成二维码并添加文字描述?下面本篇文章给大家介绍一下Vue3+qrcodejs生成二维码并添加文字描述,希望对大家有所帮助。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

一文深入详解Vue路由:vue-router一文深入详解Vue路由:vue-routerSep 01, 2022 pm 07:43 PM

本篇文章带大家详解Vue全家桶中的Vue-Router,了解一下路由的相关知识,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

手把手带你使用Vue开发一个五子棋小游戏!手把手带你使用Vue开发一个五子棋小游戏!Jun 22, 2022 pm 03:44 PM

本篇文章带大家利用Vue基础语法来写一个五子棋小游戏,希望对大家有所帮助!

手把手带你了解VUE响应式原理手把手带你了解VUE响应式原理Aug 26, 2022 pm 08:41 PM

本篇文章我们来了解 Vue2.X 响应式原理,然后我们来实现一个 vue 响应式原理(写的内容简单)实现步骤和注释写的很清晰,大家有兴趣可以耐心观看,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version