How can I use JavaScript build-in function in the Vue template?
{{ eval(item.value.substring(2)) }}
I want to use JS function eval() in {{}}, but it shows many error like:
[Vue warn]: Property or method "eval" 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://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
[Vue warn]: Error in render: "TypeError: _vm.eval is not a function"
vue.esm.js?efeb:1906 TypeError: _vm.eval is not a function
CodePudding user response:
You trying to execute eval
inside template which causes vue
to execute eval
method of your current component. If you want to use result of the global eval
function in template just create a variable in your component's data
object and store result in here. Also you can create a computed
property with eval
call in it and use this property inside template.
CodePudding user response:
First of all, this is really bad practice to use eval
at almost any case (99.9%).
Secondly, if you really want to use it, I think you need to access window
object, like answered there How to access the window object in vue js?
And then do something like this:
methods: {
eval(expr){ return window.eval(expr) }
}
After that, eval
become visible in template.
CodePudding user response:
Try this.
<template>
...
{{ item }}
...
</template>
<script>
//...
data(){
return {
item: "oldVal"
}
},
methods: {
myFunc(){
this.item = eval(item.value.substring(2)) //<-- here
}
}
//...
</script>
CodePudding user response:
Inside the template, Vue will prefix everything with a 'this.' Therefore it's not possible.
The most simple solution is to move it to the methods section of your Vue component.
EDIT: A horribly beautiful workaround that is inspired by @Mikhail Semikolenov answer would be to just create a computed property for the window object. Then you can call the eval (and any other window function) with:
{window.eval(...)}
CodePudding user response:
actually, you don't really need to use eval()
just call a method in your template as below:
<template>
...
{{subItNow(item.value)}}
</template>
and the method should return like this :
methods: {
subItNow(value){
return value.substring(2)
}
}
or if you still want to use eval
anyway just pass the result as a return in method functions