5

I want to call a plain JavaScript function from inside a Vue.js v-bind attribute. I can do it by channeling it through a Vue.js data variable, but calling a plain JavaScript function directly from v-bind produces an error.

http://jsfiddle.net/edwardtanguay/2st0fruh

How can I call a JavaScript function directly without having to map to a variable or method in Vue.js?

HTML

<div id="app">
  <div>
    The URL is: {{url}}
  </div>
  <div>
    <a target="_blank" v-bind:href="url">goto URL</a>
  </div>
  <div>
    <a target="_blank" v-bind:href="url2">goto URL2</a>
  </div>
  <div>
    <a target="_blank" v-bind:href="getUrl()">goto URL2 using javascript function</a>
  </div>
</div>

JavaScript

function getUrl() {
    return 'http://www.amazon.com';
}

var vm = new Vue({
    el: '#app',
    data: {
        url: 'http://www.google.com',
    url2: getUrl()
    }
});
0

1 Answer 1

5

In order for Vue to be able to bind itself, it needs to be part of the Vue instance. Whilst your function might be accessible under normal circumstances, it's not part of the vue instance and in turn can't be accessed.

As you have already stated, using a data prop moves it into scope of the vue instance. You could also use a computed prop for this if the value is likely to mutate.

As per this post from the vue author(Evan You) regarding using global functions:

Because implicitly falling back to globals will be a maintainability nightmare. When you look at a template you will have no idea whether a variable belongs to the component, or some globals defined by someone you have no idea where.

It's worth noting that if you feel this is something you want to do a lot, you could have a global mixin and specify some methods on there to get the Urls.

There is a way to do this but I don't recommend it:

See this fiddle

Basically, you add your own function to the Vue.prototype (this is how things like Vue Router and Vuex work):

Vue.prototype.$myFunc = function getUrl() {
    return 'http://www.amazon.com';
}

Make sure you declare it before you create your var vm = new Vue() call.

Then you can access it via $myFunc() from the template or this.$myFunc() from the vue instance itself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.