使用仅运行时的 Vue 时如何配置 Vue-router

Joh*_*kel 5 vue.js vue-router

我正在尝试根据示例使用 vue-router ,例如

let routes = [
    { path: '/',  component: MainComponent },
];

let router = new VueRouter({routes});

new Vue({  router  }).$mount('#app');
Run Code Online (Sandbox Code Playgroud)

但我总是收到这个错误:

vue.runtime.esm.js:619 [Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available.
Run Code Online (Sandbox Code Playgroud)

我可以使用渲染函数解决这个问题吗?我试过,

let routes = [];
Run Code Online (Sandbox Code Playgroud)

但还是失败了。

Joh*_*kel 5

好吧,我花了半天时间,终于让它工作了:vue-router + webpack + 仅运行时的 vue。

本教程是最有帮助的。我学到的是:

如果您使用 vue-cli,则 vue 版本位于 webpack.base.conf.js 中

  • vue.esm.js 将包含编译器
  • 视图。运行时.esm.js 将包含编译器

如果您想使用运行时,则必须更改您的main.js. 不要使用这个

new Vue({
    el: '#app',
    router,
    template: '<App/>',      //  <== This is bad
    components: { App }
});
Run Code Online (Sandbox Code Playgroud)

相反,使用这个

Vue.use(VueRouter);          // <== very important
new Vue({
    router,
    render(createElement) {
        return createElement(App);
    }
}).$mount('#app');
Run Code Online (Sandbox Code Playgroud)

您可以使用$mountel:with 运行时。两者都有效,但为$mount您提供了更大的灵活性。当然,它router是按照通常的方式创建的

let routes = [
    { path: '/', component: MainComponent },    
];
let router = new VueRouter({ routes }); 
Run Code Online (Sandbox Code Playgroud)

如果您仍然看到错误

[Vue warn]: You are using the runtime-only build of Vue
Run Code Online (Sandbox Code Playgroud)

在控制台中,然后双重确保您永远不会在代码中使用任何带有字符串的模板。即使在 *.vue 文件中,如果您尝试这样做

const Foo = { template: '<div>foo</div>' };
Run Code Online (Sandbox Code Playgroud)

它会失败。相反,您必须使用<template>标签,否则您必须使用createElement. 祝你好运!