简体   繁体   English

Vue2:如何指定 vue-router 根组件?

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

I was just upgraded to Vue2.0, and not so familiar with it.我刚升级到Vue2.0,对它不是很熟悉。

One change makes trouble for me, that the vue-router initialization [docs] is changed:一项更改给我带来了麻烦,即 vue-router 初始化[docs]已更改:

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.很快我发现以这种新案例的方式指定RootApp会使根应用程序代码对我来说模棱两可。

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.在旧情况下,每个子路由元素的$root元素产生RootApp实例,而在新情况下,它产生另一个包含RootApp实例作为其唯一子项的组件。

So, it makes trouble, is there any way to create the RootApp just acts the root node in Vue2?那么,就麻烦了,有没有什么办法可以创建RootApp只是在 Vue2 中充当根节点?

Or I guess, is there any way to create an Vue instance like the below (but failed when tried):或者我猜,有什么方法可以创建如下所示的 Vue 实例(但尝试失败):

# 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? Vue.js 2:如何从 .vue 文件初始化(构造)一个 Vue 组件?

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.您可以重构您的RootApp ,以便它的方法/数据等......都驻留在这个新的根 Vue 实例中。

This will mean also copying across RootApp 's template to your main index.html (or whatever you use) file.这也意味着将RootApp的模板复制到您的主index.html (或您使用的任何文件)文件中。 When done though everything should function as before, albeit not from a single .vue file.完成后,尽管一切都应该像以前一样运行,尽管不是来自单个.vue文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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