Vue2如何禁止DOM元素插入时生成__vue__属性以解决CSP问题
问题:Vue2(2.6.11)中禁止DOM节点生成__vue__属性以适配CSP规则
我正在使用Vue2(2.6.11),近期客户提出了CSP相关问题。为解决该问题,我在webpack-dev-server中配置了如下响应头:
headers: { 'Content-Security-Policy-Report-Only': "script-src 'self'" }
访问应用时,控制台出现如下报错:
[Report Only] Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.
排查后发现报错源于vue.runtime.esm.js中的insertBefore方法:
function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); }
原因是新插入的newNode包含__vue__属性(该属性用于vue-devtools识别实例),执行insertBefore时被当作内联脚本触发CSP规则。请问如何在Vue2中禁止生成该属性?
解决方案
要禁止Vue2在DOM节点上生成__vue__属性,只需关闭devtools功能即可——该属性正是devtools用于识别实例的标识,关闭后会自动停止生成:
全局禁用(适用于整个项目)
在项目入口文件(如main.js)中添加全局配置:
Vue.config.devtools = false;
单个实例禁用
如果仅需针对特定实例关闭,可在实例化时传入参数:
new Vue({ el: '#app', devtools: false, // 其他配置项 });
补充说明
- Vue2生产环境构建默认会自动禁用devtools,因此生产环境下不会出现
__vue__属性;问题通常出现在开发环境,需要手动配置关闭。 - 关闭devtools后将无法使用vue-devtools调试,如需调试可临时注释该配置。
内容的提问来源于stack exchange,提问作者ahwyX100
相关产品推荐
相关产品推荐

