组件引入
时间: 2023-08-18 19:17:22 浏览: 52
在 Vue 中,引入组件分为全局引入和局部引入两种方式。
1. 全局引入
全局引入组件可以在任何 Vue 实例的模板中使用。可以使用 Vue.component() 方法注册一个全局组件。
例如,我们有一个 Hello 组件:
```
<template>
<div>
<h1>Hello {{ name }}!</h1>
</div>
</template>
<script>
export default {
name: 'Hello',
props: {
name: {
type: String,
required: true
}
}
}
</script>
```
然后我们可以在任何地方使用它,只需要在 Vue 实例中先引入一下:
```
import Vue from 'vue'
import Hello from './Hello.vue'
Vue.component('hello', Hello)
```
现在,我们就可以在任何 Vue 实例的模板中使用 `<hello>` 标签了。
2. 局部引入
局部引入组件只能在当前 Vue 实例的模板中使用。可以使用 components 选项引入一个局部组件。
例如,我们有一个 Hello 组件:
```
<template>
<div>
<h1>Hello {{ name }}!</h1>
</div>
</template>
<script>
export default {
name: 'Hello',
props: {
name: {
type: String,
required: true
}
}
}
</script>
```
然后我们可以在当前 Vue 实例的 components 选项中引入一下:
```
<template>
<div>
<hello :name="name"></hello>
</div>
</template>
<script>
import Hello from './Hello.vue'
export default {
name: 'App',
components: {
Hello
},
data() {
return {
name: 'World'
}
}
}
</script>
```
现在,我们就可以在当前 Vue 实例的模板中使用 `<hello>` 标签了。