簡介
Vue.use( plugin ):安裝 Vue.js 插件。如果插件是一個對象,必須提供 install 方法。如果插件是一個函數,它會被作為 install 方法。install 方法將被作為 Vue 的參數調用。
當 install 方法被同一個插件多次調用,插件將只會被安裝一次。
Vue.js 的插件應當有一個公開方法 install 。這個方法的第一個參數是 Vue 構造器,第二個參數是一個可選的選項對象:
MyPlugin.install = function (Vue, options) { // 1. 添加全局方法或屬性 Vue.myGlobalMethod = function () { // 邏輯... } // 2. 添加全局資源 Vue.directive('my-directive', { bind (el, binding, vnode, oldVnode) { // 邏輯... } ... }) // 3. 注入組件 Vue.mixin({ created: function () { // 邏輯... } ... }) // 4. 添加實例方法 Vue.prototype.$myMethod = function (methodOptions) { // 邏輯... }}通過全局方法 Vue.use() 使用插件:
// 調用 `MyPlugin.install(Vue)`Vue.use(MyPlugin)
也可以傳入一個選項對象:
Vue.use(MyPlugin, { someOption: true })Vue.use 會自動阻止多次注冊相同插件,屆時只會注冊一次該插件。
Vue.js 官方提供的一些插件 (例如 vue-router) 在檢測到 Vue 是可訪問的全局變量時會自動調用 Vue.use()。然而在例如 CommonJS 的模塊環境中,你應該始終顯式地調用 Vue.use():
// 用 Browserify 或 webpack 提供的 CommonJS 模塊環境時var Vue = require('vue')var VueRouter = require('vue-router')// 不要忘了調用此方法Vue.use(VueRouter)實例:實現一個children組件
在main.js中使用該組件的方法:
import childModule from './components/children'Vue.use(childModule)
組件文件夾的目錄結構如下:
|-components |-children |-index.js 導出組件,并且install |-children.vue (定義自己的組件模板)
children.vue代碼如下:
import childrencomponent from './children.vue'const childrenMo = { install:function(Vue){ Vue.component('childModule',childrencomponent) }}export default childrenMo這樣就實現了一個通過vue.use調用一個全局組件。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答