我如何注冊一個 Vue 指令,以便它在我的 Vue 應用程式的所有組件中都可用?我正在使用 Vue 2
檔案說您可以注冊全域,但我在我的專案中添加了這個 Vue.directive(....)
src/directives/TestMe.js
import Vue from 'vue'
export default Vue.directive('test-me', {
inserted(el) {
el.style.backgroundColor = 'red'
},
})
src/components/SignInForm.vue
<template>
<div>
<code v-test-me>
Hello World
</code>
</div>
</template>
</script>
通過執行以下操作,我知道當前的執行方式。但是,如果我打算在我的應用程式的多個組件和頁面中使用我的指令是不切實際的。
<template>
<div>
<code v-test-me>
Hello World
</code>
</div>
</template>
<script>
import TestMe from '../../directives/TestMe'
export default {
directives: {
TestMe
}
}
</script>
根據下面的答案更新了更新的帖子。
我為每個指令創建了不同的檔案,然后有一個 index.js 檔案,我在其中匯入了所有指令。如何在我的應用程式開始時在指令檔案夾中啟動該 index.js 檔案?
// src/directives/TestMe.js
export default testMe = {
inserted(el) {
el.style.backgroundColor = 'red'
},
}
// src/directives/index.js
import testMe from './TestMe'
export default {
install(Vue) {
Vue.directive('test-me', testMe)
// Vue.directive('other-directive', myOtherDirective)
},
}
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import ???? from './directives'
const app = createApp(App)
app.use(????)
你有 globalDirectives ......這個名字是從哪里來的?
uj5u.com熱心網友回復:
編輯:我沒有讀到 OP 正在使用 Vue 2。
要呼叫.use(),您需要使用函式匯出物件
install(Vue)
如果您希望將指令作為單獨的檔案。
// src/directives/TestMe.js
const testMe = {
inserted(el) {
el.style.backgroundColor = 'red'
},
}
export default testMe
這是您注冊所有指令的地方。您可以在此處匯入檔案或僅定義您的指令。
// src/directives/index.js
import testMe from './TestMe'
// const myOtherDirective = {
// ...
// }
export default {
install (Vue) {
Vue.directive('test-me', testMe)
// Vue.directive('other-directive', myOtherDirective)
}
}
這是在 Vue 2 中注冊指令的方法
您可以使用 Vue.use 在 main.js 中注冊全域指令
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import globalDirectives from './directives'
Vue.use(globalDirectives)
const app = new Vue({
router,
store,
render: h => h(App),
})
app.$mount('#app')
這是在 Vue 3 中注冊指令的方法
您可以在 createApp 之后在 main.js 中注冊全域指令
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import globalDirectives from './directives'
const app = createApp(App)
app.use(globalDirectives)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/409527.html
標籤:
上一篇:字串陣列到樹資料結構?
