Vue.extend有什么用?

vue.js Vue.js

达蒙猪猪

2020-03-11

这足够简单,但是我没有从文档中得到所需的答案。我正在学习Vue.js,但我不太了解Vue.extend的适用范围。我得到了Vue.component,但是我看不到Vue.extend做了什么,而Vue.component没有。它仅仅是1.0版本的遗留功能吗?如果没有,在Vue 2.0中它在哪里有用?

第675篇《Vue.extend有什么用?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
神无StafanTom 2020.03.11

除了提供的答案之外,Vue.extend()如果使用TypeScript ,还有一个实际的用例可以直接调用

在大多数情况下,建议在需要时从其他文件导入组件定义,而不是使用全局注册它们Vue.component()它可以使大型项目中的事情井井有条,并更容易跟踪问题。

有了正确的库, TypeScript可以看看你的组件定义,弄清组件的类型将是当它的初始化,意味着那么它可以检查您已经定义,看看它们是否有意义(也就是说,如果你引用的功能this.foo有实际上是一个prop,数据字段,计算值或名为的方法foo如果使用Vue.component()它,则可以做到这一点,但如果使用其他使组件可用的典型方式(即导出对象文字),则不能这样做。

但是,另一种选择是导出包裹在中的组件定义Vue.extend()然后,TypeScript将能够将其识别为Vue组件并相应地运行其类型检查,但是您不必放弃导出组件的最佳实践模式,而不必在全局范围内进行注册。

Mandy梅Green 2020.03.11

以前的Vuejs.org网站上的指南中有一个文档。

http://optimizely.github.io/vuejs.org/guide/composition.html复制,该文件是从Vuejs / Vuejs.org的Vuejs版本0.10.6分叉的。

It is important to understand the difference between Vue.extend() and Vue.component(). Since Vue itself is a constructor, Vue.extend() is a class inheritance method. Its task is to create a sub-class of Vue and return the constructor. Vue.component(), on the other hand, is an asset registration method similar to Vue.directive() and Vue.filter(). Its task is to associate a given constructor with a string ID so Vue.js can pick it up in templates. When directly passing in options to Vue.component(), it calls Vue.extend() under the hood.

Vue.js支持两种不同的API范例:基于类的命令式Backbone样式API,以及基于标记的声明式Web组件样式API。如果您感到困惑,请考虑如何使用new Image()<img>标签创建图像元素每种方法都有其自身的用处,Vue.js尝试同时提供这两种方法以最大程度地提高灵活性。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android