vue开发:vue全局组件的方法

来源:互联网 发布:软件交互设计流程图 编辑:程序博客网 时间:2024/05/16 01:00

在vue项目中,可以自定义组件像vue-resource一样使用Vue.use()方法来使用,具体实现方法:

1、首先建一个自定义组件的文件夹,比如叫loading,里面有一个index.js,还有一个自定义组件loading.vue,在这个loading.vue里面就是这个组件的具体的内容,比如:

<template>    <div>        loading..............    </div></template><script>    export default {    }</script><style scoped>    div{        font-size:40px;        color:#f60;        text-align:center;    }</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

在index.js中,规定了使用这个组件的名字,以及使用方法,如:

import loadingComponent from './loading.vue'const loading={    install:function(Vue){        Vue.component('Loading',loadingComponent)    }  //'Loading'这就是后面可以使用的组件的名字,install是默认的一个方法};export default loading;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

只要在index.js中规定了install方法,就可以像一些公共的插件一样使用Vue.use()来使用,如:

import loading from './loading'Vue.use(loading)
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

这是在入口文件中引入的方法,可以看到就像vue-resource一样,可以在项目中的任何地方使用自定义的组件了,比如在home.vue中使用

<template>    <div>        <Loading></Loading>    </div></template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

这样就可以使用成功

原创粉丝点击