Vue template 如何支持多個根結點


如果你試圖創建一個沒有根結點的 vue template,像這樣:

<template> <div>Node 1</div> <div>Node 2</div> </template> 

不出意外的話你會得到一個編譯錯誤或者運行時錯誤,因為 template 必須有一個根元素

通常你可以在外面套一個div容器來解決。這個容器元素沒有顯示上的作用,只是為了滿足模板編譯的單個根節點的要求。

<template> <div><!--我只是為了哄編譯器開心--> <div>Node 1</div> <div>Node 2</div> </div> </template> 

通常情況下,像這樣加一個套也沒什么大不了的,但有時候確實需要多根結點的模板。本文我們就來看看這種情況,並提供一些可能的解決辦法繞過這個限制。

 

渲染數組

在某些情況下,可能需要用組件渲染子節點數組,以包含在某個父組件中。

例如,有些 css 特性要求特定的元素層級結構才能正確工作,比如 css grid 或 flex。在父子元素之間加一個容器是不可行的。

<template> <!--Flex won't work if there's a wrapper around the children--> <div style="display:flex"> <FlexChildren/> </div> </template> 

還有一個問題是,向組件添加包裹元素可能會導致渲染出無效的html。例如,要構造一個 table,表格行<tr>的子元素只能是<td>。

<template> <table> <tr> <!--Having a div wrapper would make this invalid html--> <TableCells/> </tr> </table> </template> 

簡而言之,單個根結點的要求意味着用組件返回子元素的這種設計模式在 vue 中行不通。

 

Fragments

單個根結點的限制在 react 中同樣是個問題,但是它在 16 版本中給出了一個解決方案,叫做fragments。用法是將多個根結點的模板包裹在一個特殊的react.Fragment 元素中:

class Columns extends React.Component { render() { return ( <React.Fragment> <td>Hello</td> <td>World</td> </React.Fragment> ); } } 

這樣就能渲染出不帶包裹元素的子元素。甚至還有個簡寫的語法<>:

class Columns extends React.Component { render() { return ( <> <td>Hello</td> <td>World</td> </> ); } } 
 

Vue 中的 Fragments

Vue 中有類似的 fragments 嗎?恐怕短期內不會有。其中的原因是虛擬 DOM 的比較算法依賴於單根節點的組件。根據 Vue 貢獻者 Linus Borg 的說法:

“允許 fragments 需要大幅改動比較算法……不僅需要它能正常工作,還要求它有較高的性能……這是一項相當繁重的任務……React 直到完全重寫了渲染層才消除了這種限制。”

 

帶有 render 函數的函數式組件

不過,函數式組件沒有這種單根結點的限制,這是因為它不需要像有狀態的組件那樣用到虛擬 DOM 的比較算法。這就是說你的組件只需要返回靜態的 HTML(不太可能,說實話),這樣就可以有多個根結點了。

還要注意一點:你需要使用 render 函數,因為 vue-loader 目前不支持多根節點特性(相關討論)。 TableRows.js

export default { functional: true, render: h => [ h('tr', [ h('td', 'foo'), h('td', 'bar'), ]), h('tr', [ h('td', 'lorem'), h('td', 'ipsum'), ]) ]; }); 

main.js

import TableRows from "TableRows";

new Vue({
  el: '#app',
  template: `<div id="app"> <table> <table-rows></table-rows> </table> </div>`, components: { TableRows } }); 

 

用指令處理

有個簡單的辦法繞過單根節點限制。需要用到自定義指令,用於操作 DOM。做法就是手動將子元素從包裹容器移動到父元素,然后刪掉這個包裹容器。

之前

<parent> <wrapper> <child/> <child/> </wrapper> </parent> 

中間步驟

<parent> <wrapper/> <child/> <child/> </parent> 

之后

<parent> <!--<wrapper/> deleted--> <child/> <child/> </parent> 

這種做法需要一些技巧和工作量,因此推薦使用一個不錯的插件 vue-fragments來完成,作者是 Julien Barbay。

資源搜索網站大全https://55wd.com 廣州品牌設計公司http://www.maiqicn.com

vue-fragments

vue-fragments 可以作為插件安裝到 Vue 項目中:

import { Plugin } from "vue-fragments"; Vue.use(Plugin); 

該插件注冊了一個全局的VFragment組件,可以用作組件模板的包裹容器,跟 React fragments 的語法類似:

<template> <v-fragment> <div>Fragment 1</div> <div>Fragment 2</div> </v-fragment> </template> 

 我也不清楚這個插件對於所有用例的健壯性如何,但從我自己的嘗試來看,用起來還不錯!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM