vue 组件命名约定
当注册组件 (或者 props) 时, 可以使用 kebab-case ,camelCase , 或 TitleCase .Vue 不关心这个.
- // 在组件定义中
- components: {
- // 使用 kebab-case 形式注册
- 'kebab-cased-component': {
- /.../
- },
- // register using camelCase
- 'camelCasedComponent': {
- /.../
- },
- // register using TitleCase
- 'TitleCasedComponent': {
- /.../
- }
- }
在 html 模版中, 请使用 kebab-case 形式:
- <!-- 在 HTML 模版中始终使用 kebab-case -->
- <kebab-cased-component>
- </kebab-cased-component>
- <camel-cased-component>
- </camel-cased-component>
- <title-cased-component>
- </title-cased-component>
当使用字符串模式时, 可以不受 HTML 的 case-insensitive 限制. 这意味实际上在模版中, 你可以使用 camelCase , TitleCase 或者 kebab-case 来引用:
(
HTML 标签名不区分大小写,<my-test></my-test > 的 nodeName 为 MY-TEST,<myTest></myTest > 的 nodeName 为 MYTEST,<MyTest></MyTest > 的 nodeName 为 MYTEST
如果在 HTML 模板中使用 myComponent 或者 MyComponent, 那么 JS 获取的节点名称都是 MYCOMPONENT, 这样就会产生歧义, 既可以认为对应的是 mycomponent 组件, 又可以认为对应的是 my-component 组件. 在 vue 中, 会认为对应的是 mycomponent 组件, 而不是 my-component 组件. 因为 vue 先对获取到的 nodeName 进行驼峰化处理, 然后再与所有组件构造函数对比, 确定对应的是哪个组件
- )
- <!-- 在字符串模版中可以用任何你喜欢的方式! -->
- <my-component></my-component>
- <myComponent></myComponent>
- <MyComponent></MyComponent>
如果组件未经 slot 元素传递内容, 你甚至可以在组件名后使用 / 使其自闭合:
<my-component/>
当然, 这只在字符串模版中有效. 因为自闭的自定义元素是无效的 HTML , 浏览器原生的解析器也无法识别它.
JavaScript 代码
- /**
- * A function that returns a sub-class constructor with the
- * given name. This gives us much nicer output when
- * logging instances in the console.
- *
- * @param {String} name
- * @return {Function}
- */
- // 组件的构造函数
- function createClass(name) {
- /* eslint-disable no-new-func */
- return new Function('return function' + classify(name) + '(options) { this._init(options) }')();
- /* eslint-enable no-new-func */
- }
- /**
- * Camelize a hyphen-delmited string.
- *
- * @param {String} str
- * @return {String}
- */
- var camelizeRE = /-(\w)/g;
- function camelize(str) {
- return str.replace(camelizeRE, toUpper);
- }
- function toUpper(_, c) {
- return c ? c.toUpperCase() : '';
- }
- /**
- * Hyphenate a camelCase string.
- *
- * @param {String} str
- * @return {String}
- */
- var hyphenateRE = /([a-z\d])([A-Z])/g;
- function hyphenate(str) {
- return str.replace(hyphenateRE, '$1-$2').toLowerCase();
- }
- /**
- * Converts hyphen/Underscore/slash delimitered names into
- * camelized classNames.
- *
- * e.g. my-component => MyComponent
- * some_else => SomeElse
- * some/comp => SomeComp
- *
- * @param {String} str
- * @return {String}
- */
- var classifyRE = /(?:^|[-_\/])(\w)/g;
- function classify(str) {
- return str.replace(classifyRE, toUpper);
- }
来源: http://www.qdfuns.com/article/17631/b11e83bcc93c8c748f1367bf44d7fcdf.html