前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue 模板中使用 console.log

vue 模板中使用 console.log

作者头像
奋飛
发布2023-04-21 21:25:54
4510
发布2023-04-21 21:25:54
举报
文章被收录于专栏:Super 前端Super 前端

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

代码语言:javascript
复制
<!-- 模板中使用全局对象属性 -->
<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 ?developer/article/2270340/undefined (reading ‘log’)

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

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

vue2 实现

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

代码语言:javascript
复制
var allowedGlobals = makeMap(
  'Infinity,?developer/article/2270340/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 进行扩展。

代码语言:javascript
复制
import Vue from 'vue'
Vue.prototype.console = { log: console.log }

vue3 实现

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

代码语言:javascript
复制
const GLOBALS_WHITE_LISTED =
  'Infinity,?developer/article/2270340/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

代码语言:javascript
复制
<script setup>
import { getCurrentInstance } from 'vue'
getCurrentInstance().appContext.config.globalProperties.console = { log: console.log }
</script>
本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-04-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • vue2 实现
  • vue3 实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com