vue 模板中使用 console.log

在 vue 工程中,你是否以为下述方式可以正常使用?

<!-- 模板中使用全局对象属性 -->
<button @click="console.log(123)">点我</button>

如果项目中这样使用,vue2 会直接抛出警告:

[vue warn]: Property or method “console” is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

vue3 会直接抛出错误

TypeError: : Cannot read properties of undefined (reading ‘log’)

模板中的表达式将被沙盒化,仅能够访问到有限的全局对象列表。该列表中会暴露常用的内置全局对象,比如 MathDate。没有显式包含在列表中的全局对象将不能在模板内表达式中访问。

如何注册能够被应用内所有组件实例访问到的全局属性?

vue2 实现

vue2 中支持的有限的全局对象列表

var allowedGlobals = makeMap(
  'Infinity,undefined,NaN,isFinite,isNaN,' +
  'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
  'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
  'require' // for Webpack/Browserify
)

vue2 中可以通过原型 Vue.prototype 进行扩展。

import Vue from 'vue'
Vue.prototype.console = {
    
     log: console.log }

vue3 实现

vue3 中支持的有限的全局对象列表

const GLOBALS_WHITE_LISTED =
  'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt'

vue3 中提供了专门的配置属性 app.config.globalProperties

<script setup>
import {
      
       getCurrentInstance } from 'vue'
getCurrentInstance().appContext.config.globalProperties.console = {
      
       log: console.log }
</script>

猜你喜欢

转载自blog.csdn.net/ligang2585116/article/details/130268720