【问题标题】:Possible template injection in vue-router like angular-ui-routervue-router 中可能的模板注入,如 angular-ui-router
【发布时间】:2017-03-13 12:55:54
【问题描述】:

我开始使用 Vue.js,而不是 AngularJS,我在vue-routerangular-ui-router 上遇到了一个问题。

每个 angular-ui-router 用户都知道这样的事情:

$stateProvider
      .state('myState', {
        url: '/my/url',
        templateUrl: 'my/template/path/template.html',
        controller: 'myTemplateController',
        controllerAs: 'myAsController'
      });

是(也许?)使用 uiRouter 的好方法之一。

当我第一次接触 uiRouter 时,我觉得用起来很舒服。

现在我正在使用 vue-router,我想知道它是否可以处理类似 templateUrl 属性的东西(我不关心其他属性,当然,对于 Vue.js 可能没有更多意义)无需每次都在 .js 文件中编写 HTML 代码(这很丑陋),而是将其抽象到局部视图中。

我问这个是因为在official documentation 中,每个示例都声明为:

const routes = [
    {
        path: '/my/url',
        component: {
            template: '<tag>html here or text or sth else...</tag>'
        }
    }
];

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

它很清楚,解释得很好,而且效果很好。但这不是我想要的。

首先在 Stackoverflow 上搜索我得到了 this thread 里面(也许?)我在问什么,但我仍然不明白在做什么。

【问题讨论】:

    标签: javascript angular-ui-router vue.js vue-router


    【解决方案1】:

    您可能想要使用.vue 文件。

    像这样创建一个 .vue 文件。

    // template.vue file
    
    <template>
     // html goes here...
    <template>
    
    <script>
     export default {
      name: 'myComponentName', // name of the component,
      created() {
      },
      // ...other vue instance properties
    
     }
    </script>
    
    <style scoped>
     // ...styles for the component
     // scoped means the styles are only applied to component
    </style>
    

    在路线中

    import myComponent from 'path/to/your/component' // .vue file
    const routes = [
        {
            path: '/my/url',
            component: myComponent
        }
    ];
    

    将组件分离成更小的组件(.vue 文件)更加灵活,可以重用和维护。
    查看此文档以创建自定义组件。 Vue Components

    【讨论】:

    • 只要确保你有一些东西可以转译 .vue 文件。用于 webpack 的 Vue-loader、用于 browserify 的 vueify 等
    • 我看到 .vue 文件类似于 html。 .vue 文件是否可以视为 .html 或 .vue 是 Vue.js 框架所需的特定键?
    【解决方案2】:

    Vue 不支持模板 url,这在 documentation 中有解释。原因是

    考虑组件,而不是模板。

    对于组件,它们可以实现为single file components,在构建过程中由 Vue 加载器处理。这有效地解决了在 JS 文件中编写 HTML 的问题。 .vue 文件被分成标记的部分

    <template>...</template>
    <script>...</script>
    

    一种独立于框架的方法是使用 Webpack/Browserify 纯文本加载器来包含文件内容(也可以在 Angular 中使用):

    path: '/my/url',
    component: {
        template: require('./component.html')
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-08
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多