7
7
8
8
const utils = require ( '../utils' )
9
9
10
+ /**
11
+ * Get the number of root element directive
12
+ * @param {VNode[] } rootElements The start tag node to check.
13
+ * @param {string } directiveName The directive name to check.
14
+ */
15
+ function getDirectiveLength ( rootElements , directiveName ) {
16
+ if ( ! directiveName ) return 0
17
+ return rootElements . filter (
18
+ ( element ) =>
19
+ element . type === 'VElement' && utils . hasDirective ( element , directiveName )
20
+ ) . length
21
+ }
22
+
10
23
module . exports = {
11
24
meta : {
12
25
type : 'problem' ,
@@ -16,10 +29,26 @@ module.exports = {
16
29
url : 'https://eslint.vuejs.org/rules/valid-template-root.html'
17
30
} ,
18
31
fixable : null ,
19
- schema : [ ]
32
+ schema : [
33
+ {
34
+ type : 'object' ,
35
+ properties : {
36
+ ignoreOnlyIfDirective : {
37
+ type : 'boolean'
38
+ }
39
+ } ,
40
+ additionalProperties : false
41
+ }
42
+ ]
20
43
} ,
21
44
/** @param {RuleContext } context */
22
45
create ( context ) {
46
+ const options = context . options [ 0 ] || { }
47
+ const ignoreOnlyIfDirective =
48
+ options . ignoreOnlyIfDirective !== undefined
49
+ ? options . ignoreOnlyIfDirective
50
+ : true
51
+
23
52
const sourceCode = context . getSourceCode ( )
24
53
25
54
return {
@@ -39,14 +68,37 @@ module.exports = {
39
68
}
40
69
}
41
70
42
- if ( hasSrc && rootElements . length > 0 ) {
43
- for ( const element of rootElements ) {
44
- context . report ( {
45
- node : element ,
46
- loc : element . loc ,
47
- message :
48
- "The template root with 'src' attribute is required to be empty."
49
- } )
71
+ if ( rootElements . length > 0 ) {
72
+ if ( hasSrc ) {
73
+ for ( const element of rootElements ) {
74
+ context . report ( {
75
+ node : element ,
76
+ loc : element . loc ,
77
+ message :
78
+ "The template root with 'src' attribute is required to be empty."
79
+ } )
80
+ }
81
+ }
82
+
83
+ if ( ! ignoreOnlyIfDirective ) {
84
+ const hasRootVIfLength = getDirectiveLength ( rootElements , 'if' )
85
+ const hasRootVElseLength = getDirectiveLength ( rootElements , 'else' )
86
+ const hasRootVElseIfLength = getDirectiveLength (
87
+ rootElements ,
88
+ 'else-if'
89
+ )
90
+ if (
91
+ hasRootVIfLength === 1 &&
92
+ hasRootVElseLength === 0 &&
93
+ hasRootVElseIfLength === 0
94
+ ) {
95
+ context . report ( {
96
+ node : element ,
97
+ loc : element . loc ,
98
+ message :
99
+ '`v-if` should not be used on root element without `v-else`.'
100
+ } )
101
+ }
50
102
}
51
103
} else if ( rootElements . length === 0 && ! hasSrc ) {
52
104
context . report ( {
0 commit comments