Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a reusable function in vue component namespace

here is my code:

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 console raise

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

define getIcon will cause name conflict, so how to define getIcon and make it only work in my component?

like image 677
chikadance Avatar asked Dec 28 '16 02:12

chikadance


1 Answers

You have to define method in methods, like following:

    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>"
      }
    }
  })

and you dont need this to invoke method in the template code.

Also see usage of v-html.

See working fiddle.

like image 121
Saurabh Avatar answered Oct 25 '22 00:10

Saurabh