1
votes

I want to use vue.js with vue-router, but the onclick doesn't work.

in App.vue:

<template>
  <div id="app">
    <hello></hello>
    <router-view></router-view>
  </div>
</template>
<script>
import hello from './components/hello/Hello.vue'

export default {
  name: 'app',
  components: {
    hello
  }
}
</script>
<style>...</style>

If I connect Hello.vue like above, I can't use onclick event (maybe another too, I can't try). After click on the button nothing happens.

but if I connect Hello.vue in router:

main.js ↓

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
import hello from './components/hello/Hello.vue'

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
});

Vue.use(VueRouter);

const routes = [
  {
    path: '/hello',
    name: 'hello',
    component: hello
  },
];

var router = new VueRouter({
  mode: 'history',
  base: __dirname,
  routes
});

const app = new Vue({
  router
}).$mount('#app');

then the button works! How I can use components not in router. For example change Hello.vue to topMenu.vue. I want use menu on all pages on site, but I don't want duplicate menu in each page component, it's not DRY!

1

1 Answers

1
votes

I found the answer. It was so easy, in my code I just replaced:

const app = new Vue({
  router
}).$mount('#app');

with:

const app = new Vue({
    router,
    render: function(createElement){
        return createElement(App)
    }
}).$mount('#app')