全局注册
uni-app 支持配置全局组件,需在 main.js 里进行全局注册,注册后就可在所有页面里使用该组件。
0.组件的创建
\components\pageHead.vue
<template>
<view>
<view class="">
{{title}}
</view>
<view class="">
{{detail}}
</view>
</view>
</template>
<script>
export default {
name: "pageHead",
props: {
title: '',
detail: '',
}
}
</script>
1.main.js 里进行全局导入和注册
import Vue from 'vue'
import App from './App'
App.mpType = 'app'
// 全局注册
import pageHead from 'components/pageHead.vue'
Vue.component('pageHead', pageHead)
2.index.vue 里可直接使用组件
<template>
<div>
<pageHead :title="title" :detail="detail"></pageHead>
</div>
</template>
<script>
export default {
onLoad() {
},
data() {
return {
title: "hello",
detail:"你好"
}
},
}
</script>
局部注册
页面引入组件方式
1.传统vue规范: 在 index.vue 页面中,通过 import 方式引入组件 ,在 components 选项中定义你想要使用的组件。
<template>
<div>
<pageHead :title="title" :detail="detail"></pageHead>
</div>
</template>
<script>
import pageHead from '../../components/pageFooter.vue';
export default {
components: {
pageHead
},
onLoad() {
},
data() {
return {
title: "hello",
detail: "你好"
}
},
}
</script>
总结步骤2步,先import 引入后components注册
2.通过uni-app的easycom: 将组件引入精简为一步。只要组件安装在项目的 components 目录下,并符合 components/组件名称/组件名称.vue 目录结构。就可以不用引用、注册,直接在页面中使用。
举例:主要是需要符合路径规范---------最方便
\components\pageHead\pageHead.vue
<template>
<div>
<pageHead :title="title" :detail="detail"></pageHead>
</div>
</template>
<script>
export default {
data() {
return {
title: "hello",
detail: "你好"
}
},
}
</script>
easycom是自动开启的,不需要手动开启,最方便
不管components目录下安装了多少组件,easycom打包后会自动剔除没有使用的组件,对组件库的使用尤为友好。
原文出处