{T}

配置项详解

silent

类型boolean

默认值false

作用:取消 Vue 所有的日志与警告。

javascript
Vue.config.silent = true;

适用场景

  • 生产环境,减少控制台输出
  • 单元测试,避免警告干扰测试结果
  • 需要完全静默运行的环境

注意事项

javascript
// 开发环境建议保持默认值
if (process.env.NODE_ENV === 'production') {
  Vue.config.silent = true;
}

optionMergeStrategies

类型{ [key: string]: Function }

默认值{}

作用:自定义合并策略的选项。合并策略函数接收三个参数:

  1. parent:父实例上定义的该选项的值
  2. child:子实例上定义的该选项的值
  3. vm:Vue 实例上下文
javascript
// 自定义选项合并策略
Vue.config.optionMergeStrategies.myOption = function (parent, child, vm) {
  return child || parent;
};

// 数字累加策略
Vue.config.optionMergeStrategies.myNumber = function (parent, child, vm) {
  return (parent || 0) + (child || 0);
};

const Parent = Vue.extend({
  myNumber: 10
});

const Child = Parent.extend({
  myNumber: 5
});

// Child.options.myNumber = 15 (10 + 5)

常见合并策略示例

javascript
// 继承 Vue 默认的合并策略
const mergeStrategies = Vue.config.optionMergeStrategies;

// 自定义方法合并策略(合并而非覆盖)
Vue.config.optionMergeStrategies.customMethods = function (parent, child) {
  if (!parent && !child) return {};
  if (!parent) return child;
  if (!child) return parent;

  // 合并父子方法
  return Object.assign({}, parent, child);
};

// 数组合并策略
Vue.config.optionMergeStrategies.customArray = function (parent, child) {
  const parentArr = parent || [];
  const childArr = child || [];
  return parentArr.concat(childArr);
};

完整示例

html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>optionMergeStrategies 示例</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </head>
  <body>
    <div id="app"></div>

    <script>
      // 定义自定义选项的合并策略:权限级别取最大值
      Vue.config.optionMergeStrategies.permission = function (
        parent,
        child,
        vm
      ) {
        const parentLevel = parent || 0;
        const childLevel = child || 0;
        return Math.max(parentLevel, childLevel);
      };

      // 父组件:权限级别 2
      const AdminComponent = Vue.extend({
        permission: 2,
        created() {
          console.log('Admin permission:', this.$options.permission);
        },
      });

      // 子组件:权限级别 3
      const SuperAdminComponent = AdminComponent.extend({
        permission: 3,
        created() {
          console.log('SuperAdmin permission:', this.$options.permission);
          // 输出: 3 (Math.max(2, 3))
        },
      });

      new SuperAdminComponent().$mount('#app');
    </script>
  </body>
</html>

devtools

类型boolean

默认值:开发版 true,生产版 false

作用:配置是否允许 vue-devtools 检查代码。

javascript
// 务必在加载 Vue 之后,立即同步设置
Vue.config.devtools = true;

适用场景

  • 开发环境:保持默认 true,方便调试
  • 生产环境:保持默认 false,避免信息泄露
  • 特殊调试需求:在生产版中临时启用 devtools
javascript
// 根据环境自动配置
if (process.env.NODE_ENV === 'development') {
  Vue.config.devtools = true;
} else {
  Vue.config.devtools = false;
}

errorHandler

类型Function

默认值undefined

作用:指定组件的渲染和观察期间未捕获错误的处理函数。

参数

参数类型说明
errError错误对象
vmVue发生错误的 Vue 实例
infostringVue 特定的错误信息(2.2.0+)
javascript
Vue.config.errorHandler = function (err, vm, info) {
  console.error('全局错误捕获:');
  console.error('错误信息:', err.message);
  console.error('错误堆栈:', err.stack);
  console.error('Vue 实例:', vm);
  console.error('错误来源:', info);
};

错误捕获范围(版本演进)

版本捕获范围
2.0.0+组件渲染和观察期间的错误
2.2.0+组件生命周期钩子里的错误
2.4.0+Vue 自定义事件处理函数内部的错误
2.6.0+v-on DOM 监听器内部抛出的错误、Promise 链错误

集成错误追踪服务

javascript
// 集成 Sentry
import * as Sentry from '@sentry/browser';

Vue.config.errorHandler = function (err, vm, info) {
  Sentry.captureException(err, {
    extra: {
      componentName: vm.$options.name,
      info: info,
      props: vm.$options.propsData,
    },
  });

  // 也可以同时输出到控制台
  console.error(err);
};

// 集成自定义错误上报
Vue.config.errorHandler = function (err, vm, info) {
  fetch('/api/log-error', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      message: err.message,
      stack: err.stack,
      component: vm.$options.name,
      info: info,
      url: window.location.href,
      timestamp: Date.now(),
    }),
  });
};

完整示例

html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>errorHandler 示例</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <style>
      .container {
        max-width: 600px;
        margin: 50px auto;
        padding: 20px;
        font-family: Arial, sans-serif;
      }
      .error-log {
        background: #fff5f5;
        border: 1px solid #fc8181;
        border-radius: 5px;
        padding: 15px;
        margin-top: 20px;
        font-family: monospace;
        font-size: 12px;
        white-space: pre-wrap;
      }
      .btn {
        padding: 10px 20px;
        margin: 5px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        background: #667eea;
        color: white;
      }
    </style>
  </head>
  <body>
    <div id="app" class="container">
      <h2>全局错误处理演示</h2>
      <button class="btn" @click="triggerError">触发同步错误</button>
      <button class="btn" @click="triggerAsyncError">触发异步错误</button>
      <button class="btn" @click="triggerLifecycleError">
        触发生命周期错误
      </button>
      <div class="error-log" v-if="errorLog">
        <strong>捕获的错误:</strong>
        {{ errorLog }}
      </div>
    </div>

    <script>
      // 全局错误处理
      Vue.config.errorHandler = function (err, vm, info) {
        vm.errorLog = `[${new Date().toLocaleTimeString()}] ${info}: ${
          err.message
        }`;
        console.error('全局错误:', err, info);
      };

      new Vue({
        el: '#app',
        data: {
          errorLog: '',
        },
        methods: {
          triggerError() {
            throw new Error('这是一个同步错误');
          },
          async triggerAsyncError() {
            throw new Error('这是一个异步错误');
          },
        },
        created() {
          // 这里故意留空,用于触发生命周期错误
        },
        mounted() {
          // 演示 v-on 错误
          // this.triggerLifecycleError();
        },
      });
    </script>
  </body>
</html>

warnHandler

类型Function

默认值undefined

版本:2.4.0+

作用:为 Vue 的运行时警告赋予一个自定义处理函数。仅开发者环境生效,生产环境会被忽略。

参数

参数类型说明
msgstring警告信息
vmVue发生警告的 Vue 实例
tracestring组件的继承关系追踪
javascript
Vue.config.warnHandler = function (msg, vm, trace) {
  console.warn('Vue 警告:');
  console.warn('信息:', msg);
  console.warn('组件:', vm.$options.name || '匿名组件');
  console.warn('组件追踪:', trace);
};

使用场景

javascript
// 过滤特定警告
Vue.config.warnHandler = function (msg, vm, trace) {
  // 忽略某些已知警告
  if (msg.includes('Unknown custom element')) {
    return; // 不显示此警告
  }

  // 其他警告正常显示
  console.warn(msg, trace);
};

// 收集警告用于分析
const warnings = [];
Vue.config.warnHandler = function (msg, vm, trace) {
  warnings.push({
    message: msg,
    component: vm.$options.name,
    trace: trace,
    timestamp: Date.now(),
  });
};

ignoredElements

类型Array<string | RegExp>

默认值[]

作用:使 Vue 忽略在 Vue 之外的自定义元素,避免 Unknown custom element 警告。

javascript
Vue.config.ignoredElements = [
  'my-custom-web-component',
  'another-web-component',
  // 用正则忽略所有 "ion-" 开头的元素(2.5+)
  /^ion-/,
];

适用场景

  • 使用 Web Components
  • 集成第三方 UI 库的自定义元素
  • 使用 Ionic 等移动端框架

完整示例

html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>ignoredElements 示例</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <!-- Web Components(Vue 不会警告) -->
      <my-web-component></my-web-component>
      <ion-button>Ion Button</ion-button>
      <ion-card>Ion Card</ion-card>
    </div>

    <script>
      // 忽略 Web Components 和 Ionic 元素
      Vue.config.ignoredElements = [
        'my-web-component',
        /^ion-/, // 忽略所有 ion- 开头的元素
      ];

      // 定义 Web Component(原生)
      class MyWebComponent extends HTMLElement {
        constructor() {
          super();
          this.innerHTML = '<span style="color: blue;">Web Component</span>';
        }
      }
      customElements.define('my-web-component', MyWebComponent);

      new Vue({
        el: '#app',
      });
    </script>
  </body>
</html>

keyCodes

类型{ [key: string]: number | Array<number> }

默认值{}

作用:给 v-on 自定义键位别名。

javascript
Vue.config.keyCodes = {
  v: 86,
  f1: 112,
  // 注意:camelCase 不可用
  // mediaPlayPause: 179,  // ❌ 不会工作
  'media-play-pause': 179, // ✅ 使用 kebab-case
  up: [38, 87], // 支持数组,多个键码映射同一别名
};
html
<!-- 使用自定义键位别名 -->
<input type="text" @keyup.v="handleVKey" />
<input type="text" @keyup.f1="showHelp" />
<input type="text" @keyup.media-play-pause="togglePlay" />
<input type="text" @keyup.up="moveUp" />

常用键码参考

别名键码说明
enter13回车键
tab9Tab 键
esc27Escape 键
space32空格键
up38上箭头
down40下箭头
left37左箭头
right39右箭头
delete[8, 46]退格/删除键

完整示例

html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>keyCodes 示例</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <style>
      .container {
        max-width: 600px;
        margin: 50px auto;
        padding: 20px;
        font-family: Arial, sans-serif;
      }
      .form-group {
        margin-bottom: 15px;
      }
      input {
        width: 100%;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 5px;
        font-size: 14px;
        box-sizing: border-box;
      }
      .hint {
        font-size: 12px;
        color: #666;
        margin-top: 5px;
      }
      .result {
        padding: 10px;
        background: #f5f5f5;
        border-radius: 5px;
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <div id="app" class="container">
      <h2>自定义键位别名</h2>

      <div class="form-group">
        <input
          type="text"
          v-model="text"
          @keyup.f1="showHelp"
          @keyup.submit="submitForm"
          @keyup.cancel="cancelForm"
          placeholder="输入内容..."
        />
        <div class="hint">按 F1 显示帮助 | F5 提交 | Esc 取消</div>
      </div>

      <div class="result">
        <p>当前输入: {{ text }}</p>
        <p>最后操作: {{ lastAction }}</p>
      </div>
    </div>

    <script>
      // 自定义键位别名
      Vue.config.keyCodes = {
        f1: 112, // F1 键
        submit: 116, // F5 键
        cancel: 27, // Esc 键
      };

      new Vue({
        el: '#app',
        data: {
          text: '',
          lastAction: '无',
        },
        methods: {
          showHelp() {
            this.lastAction = '显示帮助';
            alert('帮助信息:这是一个演示自定义键位的示例');
          },
          submitForm() {
            this.lastAction = '提交表单';
            alert('表单已提交: ' + this.text);
          },
          cancelForm() {
            this.lastAction = '取消表单';
            this.text = '';
          },
        },
      });
    </script>
  </body>
</html>

performance

类型boolean

默认值false(自 2.2.3 起)

版本:2.2.0+

作用:启用组件初始化、编译、渲染和打补丁的性能追踪。

前提条件

javascript
Vue.config.performance = true;

使用方法

  1. 设置 Vue.config.performance = true
  2. 打开 Chrome DevTools → Performance 面板
  3. 点击录制,操作应用
  4. 停止录制,查看性能分析结果

追踪指标

指标说明
init组件初始化
compile模板编译
render渲染函数执行
patch虚拟 DOM 打补丁

productionTip

类型boolean

默认值true

版本:2.2.0+

作用:设置为 false 以阻止 Vue 在启动时生成生产提示。

javascript
Vue.config.productionTip = false;

生产提示内容

code
You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html

适用场景

  • 开发环境不希望看到提示
  • 单元测试环境
  • 学习/演示环境

完整示例

html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Vue 全局配置完整示例</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <style>
      * {
        box-sizing: border-box;
      }
      body {
        font-family: 'Segoe UI', Arial, sans-serif;
        background: #f5f7fa;
        margin: 0;
        padding: 20px;
      }
      .container {
        max-width: 900px;
        margin: 0 auto;
        background: white;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        padding: 30px;
      }
      h1 {
        color: #333;
        border-bottom: 2px solid #667eea;
        padding-bottom: 10px;
      }
      h2 {
        color: #667eea;
        margin-top: 30px;
      }
      .config-section {
        background: #f8f9fa;
        padding: 15px;
        border-radius: 8px;
        margin: 15px 0;
      }
      .config-item {
        display: flex;
        align-items: center;
        margin: 10px 0;
        padding: 10px;
        background: white;
        border-radius: 5px;
        border-left: 3px solid #667eea;
      }
      .config-item label {
        flex: 0 0 150px;
        font-weight: bold;
        color: #333;
      }
      .config-item .value {
        color: #667eea;
      }
      .demo-area {
        margin: 20px 0;
        padding: 20px;
        background: #eef2f7;
        border-radius: 8px;
      }
      .btn {
        padding: 10px 20px;
        margin: 5px;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s;
      }
      .btn-primary {
        background: #667eea;
        color: white;
      }
      .btn-primary:hover {
        background: #5a6fd6;
      }
      .btn-danger {
        background: #fc8181;
        color: white;
      }
      .log-area {
        background: #1a1a2e;
        color: #00ff88;
        padding: 15px;
        border-radius: 5px;
        font-family: 'Courier New', monospace;
        font-size: 12px;
        max-height: 200px;
        overflow-y: auto;
        margin-top: 15px;
      }
      .log-item {
        margin: 5px 0;
      }
      .log-item.error {
        color: #ff6b6b;
      }
      .log-item.warn {
        color: #ffd93d;
      }
      input[type='text'] {
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 5px;
        font-size: 14px;
        width: 300px;
      }
    </style>
  </head>
  <body>
    <div id="app" class="container">
      <h1>Vue 2 全局配置演示</h1>

      <h2>当前配置状态</h2>
      <div class="config-section">
        <div class="config-item">
          <label>silent:</label>
          <span class="value">{{ config.silent }}</span>
        </div>
        <div class="config-item">
          <label>devtools:</label>
          <span class="value">{{ config.devtools }}</span>
        </div>
        <div class="config-item">
          <label>performance:</label>
          <span class="value">{{ config.performance }}</span>
        </div>
        <div class="config-item">
          <label>productionTip:</label>
          <span class="value">{{ config.productionTip }}</span>
        </div>
      </div>

      <h2>错误处理演示</h2>
      <div class="demo-area">
        <button class="btn btn-danger" @click="triggerError">
          触发同步错误
        </button>
        <button class="btn btn-danger" @click="triggerAsyncError">
          触发异步错误
        </button>
        <button class="btn btn-primary" @click="clearLogs">清空日志</button>
        <div class="log-area">
          <div v-for="(log, index) in logs" :key="index" :class="['log-item', log.type]">
            [{{ log.time }}] {{ log.message }}
          </div>
          <div v-if="logs.length === 0" class="log-item">暂无日志</div>
        </div>
      </div>

      <h2>自定义键位演示</h2>
      <div class="demo-area">
        <input
          type="text"
          v-model="inputText"
          @keyup.f1="addLog('info', 'F1 键被按下')"
          @keyup.submit="addLog('info', 'Submit 键被按下')"
          placeholder="按 F1 或 F5 测试自定义键位"
        />
      </div>

      <h2>Web Components 支持</h2>
      <div class="demo-area">
        <my-custom-element></my-custom-element>
        <p style="color: #666; margin-top: 10px">
          上面的自定义元素不会触发警告
        </p>
      </div>
    </div>

    <script>
      // ==================== 全局配置 ====================

      // 关闭生产提示
      Vue.config.productionTip = false;

      // 全局错误处理
      Vue.config.errorHandler = function (err, vm, info) {
        vm.addLog('error', `错误捕获: ${err.message} (${info})`);
      };

      // 警告处理
      Vue.config.warnHandler = function (msg, vm, trace) {
        console.warn('Vue Warning:', msg);
      };

      // 自定义键位
      Vue.config.keyCodes = {
        f1: 112,
        submit: 116, // F5
      };

      // 忽略自定义元素
      Vue.config.ignoredElements = ['my-custom-element'];

      // ==================== Web Component ====================

      class MyCustomElement extends HTMLElement {
        constructor() {
          super();
          this.innerHTML =
            '<span style="background: linear-gradient(135deg, #667eea, #764ba2); color: white; padding: 10px 20px; border-radius: 5px;">这是 Web Component</span>';
        }
      }
      customElements.define('my-custom-element', MyCustomElement);

      // ==================== Vue 实例 ====================

      new Vue({
        el: '#app',
        data: {
          config: {
            silent: Vue.config.silent,
            devtools: Vue.config.devtools,
            performance: Vue.config.performance,
            productionTip: Vue.config.productionTip,
          },
          logs: [],
          inputText: '',
        },
        methods: {
          addLog(type, message) {
            const now = new Date();
            const time = now.toLocaleTimeString();
            this.logs.unshift({ type, message, time });
          },
          triggerError() {
            throw new Error('这是一个同步错误');
          },
          async triggerAsyncError() {
            throw new Error('这是一个异步错误');
          },
          clearLogs() {
            this.logs = [];
          },
        },
      });
    </script>
  </body>
</html>

Vue 3 变化说明

Vue 3 中全局配置有较大变化,主要通过 app.config 进行配置:

Vue 2Vue 3说明
Vue.config.silentapp.config.silent基本一致
Vue.config.optionMergeStrategiesapp.config.optionMergeStrategies基本一致
Vue.config.devtools移除自动检测
Vue.config.errorHandlerapp.config.errorHandler基本一致
Vue.config.warnHandlerapp.config.warnHandler基本一致
Vue.config.ignoredElementsapp.config.compilerOptions.isCustomElement语法变化
Vue.config.keyCodes移除使用 Keystone API
Vue.config.performance移除使用 DevTools
Vue.config.productionTip移除不再需要

迁移示例

javascript
// Vue 2
Vue.config.errorHandler = (err, vm, info) => {
  // ...
};
Vue.config.ignoredElements = ['my-element', /^ion-/];

// Vue 3
const app = createApp(App);
app.config.errorHandler = (err, instance, info) => {
  // ...
};
app.config.compilerOptions.isCustomElement = (tag) => {
  return tag.startsWith('ion-') || tag === 'my-element';
};

最佳实践

1. 环境区分配置

javascript
// 根据环境配置
if (process.env.NODE_ENV === 'production') {
  Vue.config.silent = true;
  Vue.config.productionTip = false;
} else {
  Vue.config.devtools = true;
  Vue.config.performance = true;
}

2. 错误处理集成

javascript
// 生产环境:集成错误监控
if (process.env.NODE_ENV === 'production') {
  Vue.config.errorHandler = (err, vm, info) => {
    // 上报错误到监控系统
    trackError({
      message: err.message,
      stack: err.stack,
      component: vm.$options.name,
      info: info,
    });
  };
} else {
  // 开发环境:详细输出
  Vue.config.errorHandler = (err, vm, info) => {
    console.group('Vue Error');
    console.error('Error:', err);
    console.error('Component:', vm);
    console.error('Info:', info);
    console.groupEnd();
  };
}

3. 配置文件分离

javascript
// config/vue.js
export function setupVueConfig() {
  // 关闭生产提示
  Vue.config.productionTip = false;

  // 全局错误处理
  Vue.config.errorHandler = errorHandler;

  // 自定义键位
  Object.assign(Vue.config.keyCodes, customKeyCodes);

  // 忽略元素
  Vue.config.ignoredElements = ignoredElements;
}

// main.js
import { setupVueConfig } from './config/vue';

setupVueConfig();

new Vue({
  // ...
});

4. 开发辅助配置

javascript
// 仅开发环境
if (process.env.NODE_ENV === 'development') {
  // 性能追踪
  Vue.config.performance = true;

  // 警告处理(收集警告信息)
  const warnings = [];
  Vue.config.warnHandler = (msg, vm, trace) => {
    warnings.push({ msg, trace, time: Date.now() });
  };

  // 暴露到全局方便调试
  window.__VueWarnings = warnings;
}

常见问题

Q1: 配置不生效怎么办?

原因:配置必须在创建 Vue 实例之前设置。

javascript
// ❌ 错误:配置太晚
new Vue({ el: '#app' });
Vue.config.silent = true; // 无效!

// ✅ 正确:先配置后实例化
Vue.config.silent = true;
new Vue({ el: '#app' });

Q2: errorHandler 捕获不到错误?

检查项

  1. 确认错误发生在 Vue 管理的范围内
  2. 确认 Vue 版本支持该类型的错误捕获
  3. 确认没有 try-catch 捕获了错误
javascript
// ❌ try-catch 会阻止全局捕获
methods: {
  handleClick() {
    try {
      throw new Error('test');
    } catch (e) {
      // 错误被捕获,errorHandler 不会触发
    }
  }
}

// ✅ 让错误冒泡
methods: {
  handleClick() {
    throw new Error('test'); // errorHandler 会捕获
  }
}

Q3: keyCodes 不生效?

注意命名规范

javascript
// ❌ camelCase 不工作
Vue.config.keyCodes = {
  mediaPlayPause: 179
};

// ✅ 使用 kebab-case
Vue.config.keyCodes = {
  'media-play-pause': 179
};

Q4: ignoredElements 配置了还报错?

检查项

  1. 确认配置时机正确
  2. 确认元素名称匹配(区分大小写)
  3. 正则表达式确认正确
javascript
Vue.config.ignoredElements = [
  'MyElement', // 精确匹配
  /^my-/,      // 正则匹配(小写)
];

// 如果元素是 <MyElement>,需要精确匹配
// 如果元素是 <my-component>,正则 /^my-/ 可以匹配

Q5: 如何在生产环境启用 devtools?

javascript
// 生产版本 Vue 默认禁用 devtools
// 如需启用,必须在加载 Vue 后立即设置
Vue.config.devtools = true;

// 注意:这会暴露应用内部信息,仅用于调试

Q6: performance 配置后在哪里查看?

  1. 打开 Chrome DevTools
  2. 切换到 Performance 面板
  3. 点击录制按钮
  4. 操作应用
  5. 停止录制
  6. 在结果中查看 Vue 相关的性能标记

标记命名规则

  • 组件名 init
  • 组件名 render