javascript - 如何在 vue 组件命名空间中定义可重用函数

标签 javascript vue.js

这是我的代码:

Vue.component("ro-webview", {
  props: ["src"],
  template: `<div>
<div>
<div class="col-md-2 list-inline">
${this.getIcon("fa-arrow-left")}
${this.getIcon("fa-arrow-right")}
${this.getIcon("fa-refresh")}
</div>
<input class="col-md-10" :value="src"/>
</div>
<iframe class="col-md-12" :src="src"/>
</div>`,

  data: {
    getIcon: function (iconName) {
      return `<a class="btn btn-default" href="javascript:void(0)"><i class="fa ${iconName}" aria-hidden="true"></i></a>`
    }
  }
})

chrome 控制台提升

Uncaught TypeError: this.getIcon is not a function
  (anonymous function)

定义getIcon会引起名称冲突,那么如何定义getIcon并使其只在我的组件中起作用?

最佳答案

您必须在 methods 中定义方法,如下所示:

    Vue.component("ro-webview", {
     props: ["src"],
     template: `<div> \
      <div> \
        <div class="col-md-2 list-inline"> \
          <div v-html="getIcon('fa-arrow-left')" /> \
          <div v-html="getIcon('fa-arrow-right')" /> \
          <div v-html="getIcon('fa-refresh')" /> \
       </div> \
      <input class="col-md-10" :value="src"/> \
      </div> \
      <iframe class="col-md-12" :src="src"/> \
      </div>`,
    methods: {
      getIcon: function (iconName) {
        return "<a class='btn btn-default href='javascript:void(0)'><i class='fa " + iconName + " aria-hidden='true'></i></a>"
      }
    }
  })

并且您不需要 this 来调用模板代码中的方法。

另请参阅 v-html 的用法.

查看工作 fiddle .

关于javascript - 如何在 vue 组件命名空间中定义可重用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41354730/

相关文章:

javascript - 使用 setInterval() 进行简单的连续轮询

javascript - 使用 gulp 将多个特定文件和文件夹复制到另一个目录

javascript - 使用 .reduce 为每个名字求和点

javascript - 集合中所有 ID 的 Firebase Firestore 列表

javascript - (Vue, ChartJS) 从子组件 Canvas 上下文为图表创建渐变背景

Javascript : How to calculate the difference between two dates?

javascript - vue cli 使用目标库 : "require is not defined" when component is imported 构建

javascript - 在扩展组件的数据中使用时,扩展组件的数据未定义

javascript - 使用VueJS传递数据创建定价计划表

javascript - Vue.可拖动 : How to "drag an item onto another item" instead of adding/removing