Keenan Diggs
Keenan Diggs

Reputation: 2342

What globals are available in template expressions?

I'm reading the Vue.js guide, and I've come across the statement.

Template expressions are sandboxed and only have access to a whitelist of globals such as Math and Date. You should not attempt to access user defined globals in template expressions.

What are all the globals available in templates? That is, what is the content of the whitelist, exhaustively?

Upvotes: 0

Views: 169

Answers (2)

Thomas Betous
Thomas Betous

Reputation: 5123

From what I understood from source code globals are declared in a variable and make it available via a proxy between vm instance and template :

  const 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
  )

So gobals available in template are :

  • Infinity
  • undefined
  • NaN
  • isFinite
  • isNaN
  • parseFloat
  • parseInt
  • decodeURI
  • decodeURIComponent
  • encodeURI
  • encodeURIComponent
  • Math
  • Number
  • Date
  • Array
  • Object
  • Boolean
  • String
  • RegExp
  • Map
  • Set
  • JSON
  • Intl
  • require

If you try to put in your template a reference that is not whitelisted or not in your vm instance then you will have this warning :

  Property or method "${key}" 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. 

Upvotes: 1

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827178

Vue.js defines the whitelist of globals in the core/instance/proxy.js file:

//...

  const 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
  )

// ...

When Vue compiles the template, the string interpolations are processed, and if you reference a global that is not whitelisted, you will have a warning on Development.

If you are curious about how templates are compiled to render functions, look through the template explorer.

Upvotes: 1

Related Questions