vue中自定义组件(插件)

时间:2023-03-08 18:57:56
vue中自定义组件(插件)

vue中自定义组件(插件)

原创 2017年01月04日 22:46:43

在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>

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


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

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

import loading from './loading'

Vue.use(loading)

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

<template>
<div>
<Loading></Loading>
</div>
</template>

这样就可以使用成功