Table of Contents
Component-based thinking
Component communication
$props
Contains attribute bindings and events in the parent scope that are not components
v-model
自定义组件
改变默认参数
样式绑定相关
class
style
Home Web Front-end Vue.js What are the common API knowledge points for vue3 component development?

What are the common API knowledge points for vue3 component development?

May 16, 2023 pm 10:55 PM
vue3 api

    Component-based thinking

    Why use component-based development?

    Currently popular front-end frameworks such as Vue React will complete business requirements by writing components, which is component-based development. Including small program development, the idea of ​​component development will also be used.

    Analyze componentized ideas to develop applications:

    • Split a complete page into many small components

    • Each Each component is used to complete a functional module of the page

    • Each component can also be subdivided (parent and child components)

    • General components can be duplicated Use different pages

    A Vue page should be organized like a nested component tree:

    What are the common API knowledge points for vue3 component development?

    vue3 Entry file:

    import { createApp } from 'vue';
    import App from './App.vue';
    
    createApp(App).mount('#app');
    Copy after login

    createApp() The function passes in an App, App is a component and is the root component of the project.

    The following will analyze the common methods of component development in Vue3.

    Component communication

    $props

    • ##$props Used to pass data to sub-components

    • <p> $props: {{$props}} </p>
      Copy after login
    • <script setup> You need to use definePropsApi to get props

    • const props = defineProps({
        num: Number,
      })
      Copy after login
      ## in syntactic sugar #$emits

      ##$emit
    • Method used to call the parent component

      <button @click="$emit(&#39;add&#39;)">
        add
      </button>
      Copy after login

      <script setup>
    • You need to use

      defineEmitsApi statement emits##<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;button @click=&quot;add&quot;&gt;{{ num }}&lt;/button&gt; const emits = defineEmits([&amp;#39;add&amp;#39;]) function add() { emits(&amp;#39;add&amp;#39;) }</pre><div class="contentsignin">Copy after login</div></div>$parent

    in syntactic sugar

    $parent
      is used to obtain the parent component instance object.
    • <script setup>
    • The component instance will not be exposed, and using
    $parent

    directly in the template will return an empty object. In order to specify the properties to be exposed in the <script setup> component, use the

    defineExpose

    compiler macro: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>const parData = ref(&quot;父组件数据&quot;); defineExpose({ parData, })</pre><div class="contentsignin">Copy after login</div></div> Subcomponent: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;p&gt;父组件 parData: {{$parent.parData}}&lt;/p&gt;</pre><div class="contentsignin">Copy after login</div></div>$attrs

    Contains attribute bindings and events in the parent scope that are not components

    props
      or custom events.
    • Sub component:

      <Foo a="a" b="b" :num="num" @add="add" />
      Copy after login
    • In the parent component, the value of
    $attrs

    is

    { "a": "a", "b": "b" }

    . When a component does not declare any props, this will contain the bindings of all parent scopes and can be passed through

    v-bind="$attrs"
      Enter internal components - This is very useful when creating higher-order components, for example:
    • Parent component:

      <Bar :age=18 sex="boy" />
      Copy after login
    • Child component
    Bar.vue

    <p v-bind="$attrs">将$attrs对象绑定到当前标签</p>
    Copy after login

    View the DOM in the browser, age and sex are bound to the

    p

    tag as attributes. ##<script setup>

    , you need to use
      useAttrs
    • import { useAttrs } from &#39;vue&#39;;
      
      const attrs = useAttrs();
      console.log(attrs.sex); // boy
      Copy after login
      proviede & inject

    For cross-level/multi-level component communication

    • The parent component has a

      provide

      option to provide data, Child components have an
    • inject
    • option to start using this data.

      Parent component:

      provide("user", "kong");
      provide("pass", 123456);
      Copy after login

      Children component:
    • const user = inject("user");
      const pass = inject("pass");
      Copy after login
    Slot

    is used for content distribution, will

    The element serves as an outlet for carrying distribution content.

    SlotComp Component

    <template>
      <div :>
        <slot name="head"></slot>
      </div>
      <div :>
        <slot name="foot"></slot>
      </div>
    </template>
    Copy after login

    Use the above component

              <SlotComp>
                <template v-slot:head>
                  <p>head插槽</p>
                </template>
                <template v-slot:foot>
                  <p>foot插槽</p>
                </template>
              </SlotComp>
    Copy after login
    SlotComp

    The component has the

    name

    attribute The contents of the

    slot slot will be replaced. The replaced content needs to use the v-slot directive in the parent component to provide the slot with the content you want to display. Rendering scope

                <template v-slot:foot>
                  <p>foot插槽</p>
                  {{msg}}
                  {{items}}
                </template>
    Copy after login
    In the above example, {{items}}

    will not display data.

    All content in the parent template is compiled in the parent scope; all content in the child template is compiled in the child scope.

    Scope slot

    Let the slot content access the data only available in the subcomponent:

    <slot name="head" :item="items"></slot>
    Copy after login
    Slot content:

                <template v-slot:head = "slotProps">
                  <p v-for="i in slotProps.item">{{i}}</p>
                </template>
    Copy after login

    The attribute bound to the

    element is called the

    slot prop

    . Now, in the parent scope, we can use

    v-slot with a value to define the name of the slot prop we provide, in this case slotProps. v-modelForm component

    Apply

    v-model

    to the form to achieve two-way binding:
      <input v-model="text" />
      Copy after login

      自定义组件

      • v-model 应用在自定义组件上面:

      父组件中使用自定义组件:

      const msg = ref(&#39;hello world!&#39;);
      
      <ModelComp v-model="msg"></ModelComp>
      Copy after login

      相当于:

                <ModelComp 
                  :modelValue="msg"
                   @update:modelValue="msg = $event"
                >
                </ModelComp>
      Copy after login

      自定义组件ModelComp.vue中:

      const props = defineProps({
        modelValue: String
      })
      const emits = defineEmits([
        "update:modelValue"
      ])
      
      const text = ref("请输入..");
      
      // text改变时执行
      watch(text,()=>{
        emits("update:modelValue",text.value);
      })
      Copy after login

      改变默认参数

      • 未设置参数时如上,默认绑定的参数是 modelValue update:modelValue

      设置v-model参数:

      <ModelComp v-model:show="show"></ModelComp>
      Copy after login

      相当于:

                <ModelComp 
                  :show="showFlag"
                   @update:show="showFlag = $event"
                >
                </ModelComp>
      Copy after login

      自定义组件ModelComp.vue中:

      const props = defineProps({
        show: Boolean
      })
      const emits = defineEmits([
        "update:show",
      ])
      Copy after login

      样式绑定相关

      class

      class绑定:根据需求动态绑定class样式时可以使用一下几种方法

      写法1:对象语法

      <button @click="changeColor" :class="{ active: isActive }">
          点击切换我的文体颜色样式
      </button>
      
      const isActive = ref(false);
      const changeColor = () => {
        isActive.value = !isActive.value;
      }
      Copy after login

      写法2:对象语法

      <button @click="changeColor2" :class="classObj">
                点击切换颜色,根据计算属性
      </button>
      
      const isActive2 = reactive({
      active: false,
      })
      const classObj = computed(() => {
      return {
        active: isActive2.active,
        &#39;font-30&#39;: true,
      }
      })
      const changeColor2 = () => {
      isActive2.active = !isActive2.active
      }
      Copy after login

      写法3:数组语法

      <div :class="[activeClass, errorClass]"></div>
      Copy after login

      三目运算符写法

      <div :class="[isActive ? activeClass : &#39;&#39;, errorClass]"></div>
      Copy after login

      数组语法中结合对象语法使用

      <div :class="[{ active: isActive }, errorClass]"></div>
      Copy after login

      style

      动态绑定行内style样式

      三种方式:html代码

            <p :>style绑定</p>
      Copy after login
            <p :>style对象绑定(直接绑定到一个对象,代码更清新)</p>
      Copy after login
           <p :>style数组绑定</p>
      Copy after login

      js 代码

      const colorRed = ref(&#39;#f00&#39;)
      const styleObj = reactive({
        fontSize: &#39;30px&#39;,
      })
      const styleObjRed = reactive({
        color: &#39;#f00&#39;,
      })
      Copy after login

      The above is the detailed content of What are the common API knowledge points for vue3 component development?. For more information, please follow other related articles on the PHP Chinese website!

      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

      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

      Video Face Swap

      Video Face Swap

      Swap faces in any video effortlessly with our completely free AI face swap tool!

      Hot Article

      Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
      3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
      Nordhold: Fusion System, Explained
      3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
      Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
      3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

      Hot Tools

      Notepad++7.3.1

      Notepad++7.3.1

      Easy-to-use and free code editor

      SublimeText3 Chinese version

      SublimeText3 Chinese version

      Chinese version, very easy to use

      Zend Studio 13.0.1

      Zend Studio 13.0.1

      Powerful PHP integrated development environment

      Dreamweaver CS6

      Dreamweaver CS6

      Visual web development tools

      SublimeText3 Mac version

      SublimeText3 Mac version

      God-level code editing software (SublimeText3)

      Hot Topics

      Java Tutorial
      1666
      14
      PHP Tutorial
      1273
      29
      C# Tutorial
      1253
      24
      How to crawl and process data by calling API interface in PHP project? How to crawl and process data by calling API interface in PHP project? Sep 05, 2023 am 08:41 AM

      How to crawl and process data by calling API interface in PHP project? 1. Introduction In PHP projects, we often need to crawl data from other websites and process these data. Many websites provide API interfaces, and we can obtain data by calling these interfaces. This article will introduce how to use PHP to call the API interface to crawl and process data. 2. Obtain the URL and parameters of the API interface. Before starting, we need to obtain the URL of the target API interface and the required parameters.

      Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

      Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

      Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

      OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

      Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

      Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

      React API Call Guide: How to interact and transfer data with the backend API React API Call Guide: How to interact and transfer data with the backend API Sep 26, 2023 am 10:19 AM

      ReactAPI Call Guide: How to interact with and transfer data to the backend API Overview: In modern web development, interacting with and transferring data to the backend API is a common need. React, as a popular front-end framework, provides some powerful tools and features to simplify this process. This article will introduce how to use React to call the backend API, including basic GET and POST requests, and provide specific code examples. Install the required dependencies: First, make sure Axi is installed in the project

      How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

      Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

      What are the life cycles of vue3 What are the life cycles of vue3 Feb 01, 2024 pm 04:33 PM

      vue3的生命周期:1、beforeCreate;2、created;3、beforeMount;4、mounted;5、beforeUpdate;6、updated;7、beforeDestroy;8、destroyed;9、activated;10、deactivated;11、errorCaptured;12、getDerivedStateFromProps等等

      Insomnia Tutorial: How to use the PHP API interface Insomnia Tutorial: How to use the PHP API interface Jan 22, 2024 am 11:21 AM

      PHP API interface: How to use Insomnia Insomnia is a powerful API testing and debugging tool. It can help developers quickly and easily test and verify API interfaces. It supports multiple programming languages ​​​​and protocols, including PHP. This article will introduce how to use Insomnia to test PHPAPI interface. Step 1: Install InsomniaInsomnia is a cross-platform application that supports Windows, MacOS, and Linux.

      See all articles