vue3組件化開發常用API

語言: CN / TW / HK

theme: vue-pro highlight: a11y-dark


持續創作,加速成長!這是我參與「掘金日新計劃 · 6 月更文挑戰」的第5天,點擊查看活動詳情

組件化思想

為什麼使用組件化開發?

當前前端比較流行的 Vue React 等框架,都會通過編寫組件來完成業務需求,也就是組件化開發。包括小程序開發也會用到組件化開發的思想。

分析組件化思想開發應用程序:

  • 將一個完整頁面拆分成很多個小組件
  • 每個組件用於完成頁面的一個功能模塊
  • 每一個組件還可以細分 (父子組件)
  • 通用的組件可以複用到不同的頁面

一個 Vue 的頁面,應該像是棵嵌套的組件樹的形式來組織:

components.png

vue3 入口文件:

```js import { createApp } from 'vue'; import App from './App.vue';

createApp(App).mount('#app'); ```

createApp()函數傳入了一個AppApp 就是一個組件,是項目的根組件。

下面將分析 Vue3 中組件化開發的常用方法。

組件通訊

$props

  • $props 用於向子組件傳遞數據

```vue

$props: {{$props}}

```

  • <script setup> 語法糖中需要使用 definePropsApi獲取props

js const props = defineProps({ num: Number, })

$emits

  • $emit 用於調用父級組件的方法

vue <button @click="$emit('add')"> add </button>

  • <script setup> 語法糖中需要使用 defineEmitsApi聲明emits

```vue

const emits = defineEmits(['add']) function add() { emits('add') } ```

$parent

  • $parent用於獲取父組件實例對象。

<script setup> 中組件實例不會暴露出來,直接在模板中使用$parent會返回一個空對象。

為了在 <script setup> 組件中明確要暴露出去的屬性,使用 defineExpose 編譯器宏:

js const parData = ref("父組件數據"); defineExpose({ parData, }) 子組件:

```vue

父組件 parData: {{$parent.parData}}

```

$attrs

  • 包含了父作用域中不作為組件 props 或自定義事件的 attribute 綁定和事件。

子組件:

js <Foo a="a" b="b" :num="num" @add="add" /> 在父組件中,$attrs 的值就是 { "a": "a", "b": "b" }

  • 當一個組件沒有聲明任何 prop 時,這裏會包含所有父作用域的綁定,並且可以通過 v-bind="$attrs" 傳入內部組件——這在創建高階的組件時會非常有用,舉個例子:

父組件:

js <Bar :age=18 sex="boy" /> 子組件 Bar.vue

```js

將$attrs對象綁定到當前標籤

`` 在瀏覽器查看DOM,age 和 sex作為屬性被綁定到了這個p`標籤上面。

  • <script setup>中,需要使用useAttrs

```js import { useAttrs } from 'vue';

const attrs = useAttrs(); console.log(attrs.sex); // boy ```

proviede & inject

  • 用於跨層級/多層級的組件通信
  • 父組件有一個 provide 選項來提供數據,子組件有一個 inject 選項來開始使用這些數據。

父級組件:

js provide("user", "kong"); provide("pass", 123456);

子孫級組件:

js const user = inject("user"); const pass = inject("pass");

插槽 slot

用於內容分發,將 <slot> 元素作為承載分發內容的出口。

SlotComp 組件 ```js ```

使用上面的組件

js <SlotComp> <template v-slot:head> <p>head插槽</p> </template> <template v-slot:foot> <p>foot插槽</p> </template> </SlotComp>

SlotComp 組件中帶 name屬性的 slot插槽內容,會被替換。被替換的內容 需要在父組件中使用 v-slot指令為插槽提供想要顯示的內容。

渲染作用域

js <template v-slot:foot> <p>foot插槽</p> {{msg}} {{items}} </template>

上面的例子,{{items}} 不會顯示數據。

父級模板裏的所有內容都是在父級作用域中編譯的;子模板裏的所有內容都是在子作用域中編譯的。

作用域插槽

讓插槽的內容訪問子組件才有的數據:

js <slot name="head" :item="items"></slot>

插槽內容: js <template v-slot:head = "slotProps"> <p v-for="i in slotProps.item">{{i}}</p> </template>

綁定在 <slot> 元素上的 attribute 被稱為插槽 prop。現在,在父級作用域中,我們可以使用帶值的 v-slot 來定義我們提供的插槽 prop 的名字,本例中就是slotProps

v-model

表單組件

  • v-model 應用在表單上面,實現雙向綁定: js <input v-model="text" />

自定義組件

  • v-model 應用在自定義組件上面:

父組件中使用自定義組件: ```js const msg = ref('hello world!');

相當於:js 自定義組件`ModelComp.vue`中:js const props = defineProps({ modelValue: String }) const emits = defineEmits([ "update:modelValue" ])

const text = ref("請輸入..");

// text改變時執行 watch(text,()=>{ emits("update:modelValue",text.value); }) ```

改變默認參數

  • 未設置參數時如上,默認綁定的參數是 modelValue update:modelValue 設置v-model參數:

js <ModelComp v-model:show="show"></ModelComp>

相當於: js <ModelComp :show="showFlag" @update:show="showFlag = $event" > </ModelComp>

自定義組件ModelComp.vue中: js const props = defineProps({ show: Boolean }) const emits = defineEmits([ "update:show", ])

樣式綁定相關

class

class綁定:根據需求動態綁定class樣式時可以使用一下幾種方法

寫法1:對象語法 ```js

const isActive = ref(false); const changeColor = () => { isActive.value = !isActive.value; } ``` 寫法2:對象語法

```js

const isActive2 = reactive({ active: false, }) const classObj = computed(() => { return { active: isActive2.active, 'font-30': true, } }) const changeColor2 = () => { isActive2.active = !isActive2.active } 寫法3:數組語法html

三目運算符寫法html

數組語法中結合對象語法使用html

```

style

動態綁定行內style樣式

三種方式:html代碼 js <p :style="{ color: colorRed }">style綁定</p> js <p :style="styleObj">style對象綁定(直接綁定到一個對象,代碼更清新)</p> js <p :style="[styleObj, styleObjRed]">style數組綁定</p> js 代碼 js const colorRed = ref('#f00') const styleObj = reactive({ fontSize: '30px', }) const styleObjRed = reactive({ color: '#f00', })

代碼demo地址 https://github.com/kongcodes/vue3study

從0開始vue3項目搭建