vue中自定義元件(外掛)
阿新 • • 發佈:2019-01-01
在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 >
這樣就可以使用成功