首頁  >  問答  >  主體

如何為 Vue JS 建立自訂函數,例如created()鉤子?

<p>我應該如何創建一個插件,將名為<code>struct</code>的函數(如<code>created()</code>掛鉤)添加到所有組件? </p> <p>此外,我希望我的外掛能夠存取<code>結構</code>回傳值。 </p> <pre class="brush:js;toolbar:false;">export default { structure() { // Access to context } } </pre> <p>我必須提一下我使用 Inertia JS。 </p>
P粉512729862P粉512729862411 天前404

全部回覆(1)我來回復

  • P粉848442185

    P粉8484421852023-09-05 00:31:53

    您可以使用 Vue Mixins可組合項目

    兩者都可以為您提供一些共享的函數和變數。但我不知道如何在 Vue 中定義新的鉤子,例如 create() 。我必須自己在created() 中啟動你的函數。當然,您可以使用 Mixins 覆蓋現有的 Vue hooks。

    Mixin 非常方便,但不再推薦

    Composition API 中沒有 created() ,所以你必須使用onBeforeMount()onMounted()

    #這是一個使用這兩種技術的非常基本的範例

    const { createApp, ref, onBeforeMount } = Vue;
    
    const myMixin = {
      created() {
        console.log('myMixin: created()')
      }
    }
    
    const myComposable = () => {
        onBeforeMount(() => {
           console.log('myComposable: onBeforeMount()')    
        })
        const myFunction = () => console.log('myFunction()')    
        return { myFunction }
    }
    
    const App = {
      setup() {
        const { myFunction } = myComposable()
        return  { myFunction }
      },
      mixins: [myMixin]
    }
    
    const app = createApp(App)
    app.mount('#app')
    <div id="app">
      <button @click="myFunction()">myFunction()</button>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

    回覆
    0
  • 取消回覆