1

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();
});
1
  • 3
    You shouldn't. Don't use jQuery with modern frameworks. Commented Sep 5, 2019 at 7:16

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.