简体   繁体   中英

Vue2: How to specify the vue-router root component?

I was just upgraded to Vue2.0, and not so familiar with it.

One change makes trouble for me, that the vue-router initialization [docs] is changed:

In my case, the initialization code is changed as below:

Old

import RootApp from './components/RootApp.vue';

router.start(RootApp, '#app')

New

import RootApp from './components/RootApp.vue';

new Vue({
  el: '#app',
  router: router,
  render: h => h(RootApp)
})

Soon I found that specifying the RootApp in such a manner of new case make the root app code ambiguous for me.

That in old case, the $root element of each sub-route element yields the RootApp instance, while in new case, it yields another component which contains the RootApp instance as its only child.

So, it makes trouble, is there any way to create the RootApp just acts the root node in Vue2?

Or I guess, is there any way to create an Vue instance like the below (but failed when tried):

# Failed code to tell what I want

import RootApp from './component/RootApp.vue';
new RootApp({
    el: '#app',
    router: router,
});

After a long time to test, I found the last attempt is almost there, see another question:

Vue.js 2: How to initialize(construct) a Vue component from a .vue file?

The following code worked perfectly!

import RootApp from './component/RootApp.vue';
const RootAppConstructor = Vue.extend(RootApp);
new RootAppConstructor({
    el: '#app',
    router: router,
});

You could refactor your RootApp so that it's methods / data etc... all reside within this new root Vue instance.

This will mean also copying across RootApp 's template to your main index.html (or whatever you use) file. When done though everything should function as before, albeit not from a single .vue file.

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