簡體   English   中英

Vue 模板使用 JavaScript 內置函數

[英]Vue template use JavaScript build-in function

如何在 Vue 模板中使用 JavaScript 內置函數?

{{ eval(item.value.substring(2)) }}

我想在 {{}} 中使用 JS 函數 eval(),但它顯​​示了許多錯誤,例如:

[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://v2.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

您嘗試在模板中執行eval ,這會導致vue執行當前組件的eval方法。 如果您想在模板中使用全局eval函數的結果,只需在組件的data對象中創建一個變量並將結果存儲在此處。 您還可以在其中創建一個帶有eval調用的computed屬性,並在模板中使用此屬性。

首先,幾乎在任何情況下(99.9%)都使用eval是非常糟糕的做法。

其次,如果你真的想使用它,我認為你需要訪問window對象,就像那里回答的那樣How to access the window object in vue js?

然后做這樣的事情:

methods: {
 eval(expr){ return window.eval(expr) }
}

之后, eval在模板中變得可見。

在模板中,Vue 將在所有內容前加上“this”。 因此這是不可能的。

最簡單的解決方案是將其移至 Vue 組件的方法部分。

編輯:受@Mikhail Semikolenov 答案啟發的一個非常漂亮的解決方法是為窗口對象創建一個計算屬性。 然后你可以調用 eval (和任何其他窗口函數):

{window.eval(...)}

嘗試這個。

<template>
...
{{ item }}
...
</template>

<script>
//...
data(){
  return {
    item: "oldVal"
  }
},
methods: {
   myFunc(){
     this.item = eval(item.value.substring(2)) //<-- here
   }  
}
//...
</script>

實際上,您實際上並不需要使用eval()只需在模板中調用一個方法,如下所示:

<template>
    ...
    {{subItNow(item.value)}}
</template>

並且該方法應該像這樣返回:

methods: {
   subItNow(value){
        return value.substring(2)
    } 
}

或者如果您仍然想使用eval ,只需將結果作為返回值傳遞給方法函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM