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

chi*_*nce 6 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>`
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

镀铬控制台升高

Uncaught TypeError: this.getIcon is not a function
  (anonymous function)
Run Code Online (Sandbox Code Playgroud)

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

Sau*_*abh 6

您必须在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>"
      }
    }
  })
Run Code Online (Sandbox Code Playgroud)

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

另请参阅v-html的用法。

请参阅工作小提琴