在vue-router中导入组件的更短方法

时间:2018-07-22 20:32:22

标签: vue.js vuejs2 vue-router

我曾经用过这种方式:

import Home from '@/views/Home/Home.vue'
import Login from '@/views/Login/Login.vue'
import Signup from '@/views/Signup/Signup.vue'
import ForgotPassword from '@/views/ForgotPassword/ForgotPassword.vue'
import NotFound from '@/views/NotFound/NotFound.vue'
import Dashboard from '@/views/Dashboard/Dashboard.vue'
import Groups from '@/views/Groups/Groups.vue'
import Pricing from '@/views/Pricing/Pricing.vue'

有没有更短的方法?

2 个答案:

答案 0 :(得分:1)

  

我最终使用了这个:

[INFO] Results:
[INFO] 
[ERROR] Failures: 
[ERROR]   RequestAcceptTest.lambda$testAllMimeTypes$0:64->assertAccept:73
[ERROR]   RequestAcceptTest.lambda$testAllMimeTypes$0:64->assertAccept:73
[ERROR]   RequestAcceptTest.lambda$testAllMimeTypes$0:64->assertAccept:73

对于以下结构:

let importComponent = require.context('@/pages/', true, /\.vue$/)
let imports = {}

function importAll (file_paths) {
    file_paths.keys().forEach(file_path => {
        const file_name = file_path.split('/')[1]
        const path = file_path.split('.')[0]
        imports[file_name] = importComponent(file_path).default
  });
}

importAll(require.context('@/pages/', true, /\.vue$/));

完整的示例是:

-pages
 --HomePage
    -- HomePage.vue
--AboutPage
    -- AboutPage.vue

注意:您可以根据需要对其进行编辑或将其用作服务。请确保查看webpack require-context

答案 1 :(得分:-1)

没有较短的语法可以将组件导入另一个组件。

但是,对于要使用很多组件的组件,如果您使用的是Webpack(或内部使用Webpack的Vue CLI 3+),则可以在条目文件中全局一次导入它们。

Vue Docs

中的示例
    private void sendTestEmail() {
    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("to", to)
            .addFormDataPart("subject", subject)
            .addFormDataPart("message", message)
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
}

在某些情况下,这可能不是理想的行为。我建议阅读这篇文章。

简短说明:通常,您可以将import Vue from 'vue' import upperFirst from 'lodash/upperFirst' import camelCase from 'lodash/camelCase' const requireComponent = require.context( // The relative path of the components folder './components', // Whether or not to look in subfolders false, // The regular expression used to match base component filenames /Base[A-Z]\w+\.(vue|js)$/ ) requireComponent.keys().forEach(fileName => { // Get component config const componentConfig = requireComponent(fileName) // Get PascalCase name of component const componentName = upperFirst( camelCase( // Strip the leading `./` and extension from the filename fileName.replace(/^\.\/(.*)\.\w+$/, '$1') ) ) // Register component globally Vue.component( componentName, // Look for the component options on `.default`, which will // exist if the component was exported with `export default`, // otherwise fall back to module's root. componentConfig.default || componentConfig ) }) 的扩展名.vue保留下来。至少更容易阅读。

相关问题