简体   繁体   中英

How do I call a global function in a vue.js child component?

The global function init() outputs a console log when the screen is loaded. However, clicking the child component button does not re-enable the init() function.

How can I call the global function init() when I click a button in my child's component?

App.vue (parent)

<template>
  <div id="app">
    <div id="nav">
      <router-link :to="{name: 'home'}">Home</router-link> |
      <router-link :to="{name: 'about'}">About</router-link>
    </div>
     <router-view></router-view>
  </div>
</template>


<script>
  import './assets/css/style.css'
  import './assets/js/commmon.js'

  export default {
  }
</script>

Home.vue (child)

<template>
  <div>
    <a href="#" id="btn_link">Home Button</a><br><br>
  </div>
</template>

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

router.js

import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    { path: '/', name: 'home', component: Home},
    { path: '/about', name: 'about', component: About},
  ]
})

function init() {
  console.log('load inti()')
}
init();

$('#btn_link').click(function(){
  init();
});

The whole idea of js modules is to stop you having, or supposedly needing, a global scope. People sometimes suggest a workaround of adding your global functions to the Vue object, which strikes me as a cure worse than the disease. My answer to this is to provide one global object in the root of your vue app, put your functions inside, then inject it into any component that needs it.

As it says in the comments, don't use jquery with Vue. Your event handler should be in the methods of the component that contains the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM