【问题标题】:Vue template use JavaScript build-in functionVue模板使用JavaScript内置函数
【发布时间】:2023-03-08 04:32:01
【问题描述】:

如何在 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://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,然后在模板代码中使用结果。
  • 我知道我可以在方法中调用它,但是我想尝试在模板中直接使用JavaScript函数。
  • 但是为什么呢?鉴于在渲染代码中运行计算是不好的做法?
  • 我只是不想在我的代码中添加更多行。我喜欢短代码。
  • 使用文档建议的计算属性。这是一种很好的做法,可以使您的模板代码保持简短。

标签: javascript vue.js templates


【解决方案1】:

您试图在模板内执行eval,这会导致vue 执行您当前组件的eval 方法。如果您想在模板中使用全局 eval 函数的结果,只需在组件的 data 对象中创建一个变量并将结果存储在此处。您也可以创建一个带有eval 调用的computed 属性,并在模板中使用此属性。

【讨论】:

    【解决方案2】:

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

    其次,如果你真的想使用它,我认为你需要访问window对象,就像回答那里How to access the window object in vue js?

    然后做这样的事情:

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

    之后,eval 在模板中可见。

    【讨论】:

      【解决方案3】:

      试试这个。

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

      【讨论】:

        【解决方案4】:

        在模板中,Vue 会在所有内容前加上“this”。因此这是不可能的。

        最简单的解决方案是将其移至 Vue 组件的方法部分。

        编辑:受@Mikhail Semikolenov 答案启发的一个非常漂亮的解决方法是为窗口对象创建一个计算属性。然后您可以使用以下命令调用 eval(和任何其他窗口函数):

        {window.eval(...)}
        

        【讨论】:

          【解决方案5】:

          其实你并不需要使用eval() 只需在您的模板中调用一个方法,如下所示:

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

          并且该方法应该像这样返回:

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

          或者如果您仍然想使用eval,只需将结果作为返回值传递给方法函数

          【讨论】:

            猜你喜欢
            • 2014-01-23
            • 2018-02-03
            • 1970-01-01
            • 2020-03-11
            • 1970-01-01
            • 2022-07-09
            • 2018-08-03
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多