首頁> web前端> Vue.js> 主體

vue.use方法怎麼用

藏色散人
發布: 2023-01-13 00:44:57
原創
2657 人瀏覽過

vue.use方法的使用:首先安裝Vue.js插件;然後透過全域方法「Vue.use()」使用插件,其語法如「vue.use(plugin, arguments)」。

vue.use方法怎麼用

本教學操作環境:windows7系統、vue2.0版本、thinkpad t480電腦。

推薦:《vue教學

官方API介紹:

Vue.use(plugin)
登入後複製

官網給的解釋是: 透過全域方法Vue.use()使用插件。

vue.use(plugin, arguments)
登入後複製

參數

{Object | function} plugin
登入後複製

用法

安裝Vue.js 外掛程式。如果插件(plugin)是一個對象,必須提供install方法。如果插件是一個函數,它會作為install方法。 install方法呼叫時,會將Vue當作參數傳入。

該方法需要在呼叫New Vue()之前被呼叫。

當install方法被同一個插件多次調用,插件將只會被安裝一次。

Element-UI範例

根據ElementUI文檔,在Vue cli搭建的專案中這樣使用ElementUI

/* mian.js */ import Vue from 'vue'; import ElementUI from 'element-ui'; // 1 import 'element-ui/lib/theme-chalk/index.css'; import App from './App.vue'; Vue.use(ElementUI); // 2 new Vue({ el: '#app', render: h => h(App) });
登入後複製

以上程式碼便完成了Element的引入,需要注意的是,樣式文件需要單獨引入。

後面就可以在Vue的單一檔案元件中直接使用 來使用Element元素。

所以這到底發生了什麼事?

1、第一個註解導入ElementUI

import ElementUI from 'element-ui' // TODO 理解如何导入模块
登入後複製

以下是src/index.js的內容。可以看到,index.js導出了一個對象,在上面的import語句中,這個物件被賦予ElementUI的變數名稱。請注意到這裡的install函數。

/* index.js */export default { version: '2.11.1', locale: locale.use, i18n: locale.i18n, install, ... };
登入後複製

2、第二處註解安裝ElementUI

Vue.use(ElementUI);
登入後複製

我們觀察到這裡使用了Vue.use方法並將ElementUI這個物件傳入。從Vue.use文件中可以得知,這會呼叫ElementUI物件的install方法,並將Vue傳入。

// install函数 const install = function(Vue, opts = {}) { locale.use(opts.locale); locale.i18n(opts.i18n); // 安装组件:通过Vue.component声明全局组件,所以我们能够直接使用而不需要声明 components.forEach(component => { Vue.component(component.name, component); }); Vue.use(InfiniteScroll); Vue.use(Loading.directive); // 在Vue的原型链上做一些小动作所以所有的Vue实例都可以访问到这些生命的变量 // 变量名使用$开头表明这是公共API属性或者方法,这是一种约定。 Vue.prototype.$ELEMENT = { size: opts.size || '', zIndex: opts.zIndex || 2000 }; // ok,这里我们看到了许多用于提示的组件都设定在Vue原型链上,所以我们可以在Vue实例内部直接使用this.$alert Vue.prototype.$loading = Loading.service; Vue.prototype.$msgbox = MessageBox; Vue.prototype.$alert = MessageBox.alert; Vue.prototype.$confirm = MessageBox.confirm; Vue.prototype.$prompt = MessageBox.prompt; Vue.prototype.$notify = Notification; Vue.prototype.$message = Message; };
登入後複製

以上是vue.use方法怎麼用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
vue
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn