Home > Web Front-end > Vue.js > body text

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

WBOY
Release: 2023-05-16 22:55:26
forward
1037 people have browsed it

    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:js;">&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:js;">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!

      Related labels:
      source:yisu.com
      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
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!