在使用vue-cli脚手架构建项目时,组件的使用步骤大致是:创建组件component,编写模板template,抛出组件给项目export,引入组件import,抛出组件给页面export。

一、创建组件

  在componets文件夹里创建新的组件文件newVue.vue,注意后缀名为.vue

vue-cli构建项目中组件的使用

vue-cli构建项目中组件的使用

  注意:组件名称不能使用html的自有标签或javascript的关键字,例如:head.vue,new.vue这样的组件名称是不符合规范的,加载的时候也会出现问题。

二、编写组件内的模板内容和样式

 template是模板的意思,模板内容就是组件将展示的具体内容
<template>
  <div>这里是模板内容</div>
</template>

   <style scoped>

      //这里可以编写样式

   </style>

  注意:模板内容只能有一个顶层html标签,例如:上面代码里将div作为顶层标签,那么所有的模板内容都必须写在这个div内部

三、抛出组件给vue项目

   通过export将组件抛出给vue项目,并将组件命名为newVue

<template>
  <div>这里是模板内容</div>
</template>

<script>
export default {
  name: 'newVue'
}
</script>

<style scoped>

</style>

四、引入组件到主组件,并将引入的组件抛出给主组件

  import newVue from '@/components/newVue'

  通过import引入组件,再通过export将引入的组件抛出给主组件,抛出多个组件用逗号隔开即可

  主组件就可以通过自定义标签调用:

  <newVue></newVue>
<template>
  <div >
    <newVue></newVue>
    <router-view/>
  </div>
</template>

<script>
import newVue from '@/components/newVue'
export default {
  components:{
    newVue
  }
}
</script>

相关文章:

  • 2021-08-05
  • 2021-11-03
  • 2022-12-23
  • 2022-01-27
  • 2021-07-10
猜你喜欢
  • 2021-08-08
  • 2022-01-11
  • 2021-12-26
  • 2021-10-20
  • 2021-12-02
  • 2022-12-23
  • 2021-10-15
相关资源
相似解决方案