主要使用了三個方法
install:(Vue)=>{},Vue.componet("注冊的組件名","封裝的組件") , Vue.use();
eg:封裝一個全局標題組件
1.建立一個titile.vue文件,將你想展示的內容寫到這個文件中
<template> <div> 我是全局標題組件 </div> </template> <script> export default { name:"title", data() { return { name: 1 } }, } </script> <style lang="less" scoped> </style>
2.建立一個titile.js文件,引入title.vue文件,將這個文件拋出
import Title from "./title.vue"; export default { install: (Vue) => { Vue.component("myTitle", Title) //這個myTitle就是你頁面中使用的 } }
3.在入口主文件中掛載組件 main.js
//自定義全局組件 import myComponets from "./components/global/title.js"; Vue.use(myComponets)
//然后在頁面中直接使用<myTitle></myTitle>就可以了
ps:vue.use()方法和在prototype掛載的區別
vue.use實際上是調用了ininUse方法,這個方法有一個參數就是傳遞的組件,這個參數(plugin)必須是array或者object;
在這個方法里面會有一個install方法,用來注冊組件,但是只有沒有注冊過的組件才會被注冊(會有一個變量instatedPlugins來判斷組件是否在該變量中存在);
而prototype只能掛載一些方法