Home  >  Q&A  >  body text

How to create custom functions for Vue JS such as created() hook?

<p>How should I create a plugin that adds a function named <code>struct</code> (like a <code>created()</code> hook) to all components? </p> <p>Also, I want my plugin to have access to the <code>structure</code> return value. </p> <pre class="brush:js;toolbar:false;">export default { structure() { // Access to context } } </pre> <p>I have to mention that I use Inertia JS. </p>
P粉512729862P粉512729862411 days ago406

reply all(1)I'll reply

  • P粉848442185

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

    You can use Vue Mixins or Combinables.

    Both can provide you with some shared functions and variables. But I don't know how to define new hooks in Vue like create() . I have to start your function in created() myself. Of course, you can use mixins to override existing Vue hooks.

    Mixin is very convenient, but is no longer recommended

    There is no created() in the Composition API, so you must use onBeforeMount() or onMounted()

    This is a very basic example using both techniques

    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>

    reply
    0
  • Cancelreply