关于vue.js:VueJS:是否有多个单个文件组件,每个组件都是一个vue实例或嵌套对象?

VueJS: are multiple Single file components each a vue instance or nested objects?

在VueJS中,是否有多个单个文件组件(作为父子组件),每个单个vue实例都嵌套在根实例中?之所以这样假设,是因为每个组件都可以具有与根Vue实例相似的相同属性,即datamethodstemplate,生命周期挂钩(mountedcreated等)或像非SFC设置中的vue实例那样说。

在我看来,任何web-pack vue-loader单文件组件设置都是作为JS对象导出并嵌套在父组件中的嵌套对象,即子代嵌套在父组件中,而父组件嵌套在单个根vue实例中。

基本上,简单地说,只有一个根实例,而SFC是嵌套对象。正如Sarah Drasner在以下链接的CSS技巧文章中所写:

You can have more than one instance in an application. Typically, we'll have one instance and several components, as the instance is the main app. src

Anybuddy能否进一步阐明哪个断言正确,即SFC是每个vue实例还是它们是单个根vue实例内的嵌套对象。如果发现后者是正确的情况,那么为什么每个人都可以拥有类似于根vue实例的生命周期挂钩。

从技术上讲,Vue如何使SFC像单独的Vue实例一样起作用,但仍是单个根实例内的嵌套对象?

谢谢


首先,"单个文件组件"和"全局组件"在它们的属性和生命周期挂钩方面没有区别。它们的区别仅在于打包方式,其他组件如何引用它们以及HTML模板的存储方式/位置。

第二,所有组件,包括" root component "都是Vue实例。如果您查看源代码,则会看到根实例是通过缺少任何父代来标识的,例如:

1
const isRoot = !vm.$parent

使用vue devtools在Vue应用程序中查看此组件树:

enter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
> var root = $vm0
> var app = $vm0.$children[0]
> var link = $vm0.$children[0].$children[0]

// How they are named in vue dev tools
> link.$options._componentTag
<"router-link"
> app.$options.__file
<"src/App.vue"

// How the root instance is identified
> !root.$parent
< true
> !app.$parent
< false
> !link.$parent
< false

// Constructors
// Each component has its own class (or prototype), but they all extend the Vue base class
> Object.getPrototypeOf(root) === Object.getPrototypeOf(Object.getPrototypeOf(app))
< true
> Object.getPrototypeOf(root) === Object.getPrototypeOf(Object.getPrototypeOf(link))
< true

因此,组件既是vue实例又是单个根vue实例内的嵌套对象。