Heim  >  Fragen und Antworten  >  Hauptteil

Wie erstelle ich benutzerdefinierte Funktionen für Vue JS, z. B. den Hook „created()“?

<p>Wie soll ich ein Plugin erstellen, das allen Komponenten eine Funktion namens <code>struct</code> hinzufügt (wie ein <code>created()</code>-Hook)? </p> <p>Außerdem möchte ich, dass mein Plugin Zugriff auf den Rückgabewert <code>Struktur</code> hat. </p> <pre class="brush:js;toolbar:false;">export default { Struktur() { // Zugriff auf Kontext } } </pre> <p>Ich muss erwähnen, dass ich Inertia JS verwende. </p>
P粉512729862P粉512729862411 Tage vor408

Antworte allen(1)Ich werde antworten

  • 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>

    Antwort
    0
  • StornierenAntwort