Vue @ 代替src 路径 文件配置,全局组件

MrYu2020-10-22VueVue

介绍

文件配置,全局组件

Vue @ 代替src 路径 vue.config.js 文件配置

'use strict'
const path = require('path')

function resolve (dir) {
  return path.join(__dirname, dir)
}
module.exports = {
  devServer: {
    proxy: process.env.VUE_APP_MOCK_SERVER
  },
  // 手动添加 @ 代替src
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    resolve: {
      alias: {
        '@': resolve('src')
      }
    }
  }
}

Vue 全局项目组件注册

img

文件结构如上图所示。

index.js
import Vue from 'vue'
// 注册全局组件   不用引用,注册组件   直接使用
const requireContext = require.context('./global', true, /\.vue$/)
requireContext.keys().forEach(fileName => {
  const componentConfig = requireContext(fileName)
  Vue.component(
    componentConfig.default.name || componentConfig.name,
    componentConfig.default || componentConfig
  )
})

WARNING

'./global' :components/global 文件 内的公共组件 vue文件 写的时候组件 一定要加name

最后 在main.js

import './components'

例:

<template>
  <div :class="className">
    <div
      class="box-header"
      :class="{'with-border': headerBorder}"
    >
      <div class="box-title">
        {{title}}
      </div>
    </div>
    <div class="box-body">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BaseBox',
  props: {
    type: {
      type: String,
      default: 'info'// 因为自定义了common css文件  此处是样式
    },
    title: {
      type: String,
      require: true
    },
    headerBorder: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
    }
  },
  computed: {
    className () {
      // 获取传入的type  根据type修改样式
      return ['box', `box-${this.type}`]
    }
  }
}
</script>