vue全局使用封装后的组件

302 阅读1分钟

1.封装组件

vue是单页面应用,每一个页面都可当作一个组件。当然组件封装的颗粒度要自己把握,如一个button按钮可能非特殊情况下就无需封装了。 通常把一组需要多处用到的基本相同的样式,如一个表格封装起来,以备复用。

封装一个HelloWorld组件,在components文件夹中创建 HelloWorld.vue 文件

<template>
	<div class="hello">{{msg}}</div>
</template>
<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "hello world!"
    };
  }
};
</script>
<style lang='less' scoped>
.hello{}
</style>

2.将所有希望用到全局的组件放到公共组件文件中[core/components.js]

import HelloWorld from '@/components/HelloWorld'
export default (Vue) => {
    Vue.component("HelloWorld", HelloWorld)
}

3.添加到全局,以供使用

import myComponents from '@/core/components'//全局公共组件

Vue.use(myComponents)

4.使用

在想要使用的页面中加入(名字要和 core/components.js中传入vue.component定义的名字一致)

<HelloWorld></HelloWorld>