国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

淺談Vue 函數(shù)式組件的使用技巧

瀏覽:89日期:2023-01-13 08:09:45

什么是函數(shù)式組件

沒有管理任何狀態(tài),也沒有監(jiān)聽任何傳遞給它的狀態(tài),也沒有生命周期方法,它只是一個接受一些 prop 的函數(shù)。簡單來說是 一個無狀態(tài)和無實例的組件

基本寫法:

Vue.component(’my-component’, { functional: true, // Props 是可選的 props: { // ... }, // 為了彌補缺少的實例 // 提供第二個參數(shù)作為上下文 render: function(createElement, context) { // ... }})

.vue 單文件組件寫法

<template functional> ...</template>

因為函數(shù)式組件沒有 this,參數(shù)就是靠 context 來傳遞的了,有如下字段的對象:

props:提供所有 prop 的對象 children:VNode 子節(jié)點的數(shù)組 slots:一個函數(shù),返回了包含所有插槽的對象 scopedSlots:(2.6.0+) 一個暴露傳入的作用域插槽的對象。也以函數(shù)形式暴露普通插槽。 data:傳遞給組件的整個數(shù)據(jù)對象,作為 createElement 的第二個參數(shù)傳入組件 parent:對父組件的引用 listeners:(2.3.0+) 一個包含了所有父組件為當前組件注冊的事件監(jiān)聽器的對象。這是 data.on 的一個別名。 injections:(2.3.0+) 如果使用了 inject 選項,則該對象包含了應當被注入的 property。

使用技巧

以下總結、都是基于使用 <template> 標簽開發(fā)函數(shù)式組件中遇到的問題

attr 與 listener 使用

平時我們在開發(fā)組件時,傳遞 prop 屬性以及事件等操作,都會使用v-bind='$attrs'和 v-on='$listeners'。而在函數(shù)式組件的寫法有所不同,attrs屬性集成在 data中。

<template functional> <div v-bind='data.attrs' v-on='listeners'> <h1>{{ props.title }}</h1> </div></template>

class 與 style 綁定

在引入函數(shù)式組件、直接綁定外層的class類名和style樣式是無效的。data.class 表示動態(tài)綁定class, data.staticClass 則表示綁定靜態(tài)class, data.staticClass 則是綁定內聯(lián)樣式TitleView.vue

<template functional> <div : :style='data.staticStyle'> <h1>{{ props.title }}</h1> </div></template>

Test.vue

<template> <title-view : /></template>

component 組件引入

函數(shù)式組件引入其他組件方式如下,具體參考:github.com/vuejs/vue/i…

<template functional> <div class='tv-button-cell'> <component :is='injections.components.TvButton' type='info' /> {{ props.title }} </component> </div></template><script>import TvButton from ’../TvButton’export default { inject: { components: { default: { TvButton } } }}</script>

$options 計算屬性

有時候需要修改prop數(shù)據(jù)源, 使用 Vue 提供的 $options 屬性,可以訪問這個特殊的方法。

<template functional> <div v-bind='data.attrs' v-on='listeners'> <h1>{{ $options.upadteName(props.title) }}</h1> </div></template><script> export default { updateName(val) { return ’hello’ + val } }</script>

總結

雖然速度和性能方面是函數(shù)式組件的優(yōu)勢、但不等于就可以濫用,所以還需要根據(jù)實際情況選擇和權衡。比如在一些展示組件。例如, buttons, tags, cards,或者頁面是靜態(tài)文本,就很適合使用函數(shù)式組件。

到此這篇關于淺談Vue 函數(shù)式組件的使用技巧的文章就介紹到這了,更多相關Vue 函數(shù)式組件內容請搜索好吧啦網以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Vue
相關文章:
主站蜘蛛池模板: 乌审旗| 兴城市| 汪清县| 永川市| 奉化市| 务川| 墨脱县| 德昌县| 梁山县| 永胜县| 清远市| 西盟| 建宁县| 陇南市| 襄樊市| 陇南市| 淮滨县| 鸡东县| 格尔木市| 吴桥县| 延寿县| 昌吉市| 万宁市| 安徽省| 修水县| 滦平县| 合山市| 乌兰浩特市| 水富县| 武强县| 乌苏市| 疏勒县| 永济市| 北辰区| 明星| 红桥区| 商洛市| 山西省| 罗定市| 丰原市| 福鼎市|