Reputation: 1164
Looking at the Vue Documentation, I can't understand how to call a function with arguments in Vue, using data already in the template.
For example,
JavaScript
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
methods: {
reverse: function (word) {
return word.split('').reverse().join('');
}
}
})
HTML
<div id="example">
<p> {{ message }} </p>
<p> {{ reverse( {{ message }} ) }} </p>
</div>
I know the HTML is wrong, but this is similar to what I'm looking to achieve.
Upvotes: 1
Views: 9981
Reputation: 6788
@Jerodev answer is correct, and it's what you were looking for.
However, for the code snippet you pasted, a computed property is the way to go:
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
reverse(){
return this.message.split('').reverse().join('');
}
}
})
<div id="example">
<p> {{ message }} </p>
<p> {{ reverse }} </p>
</div>
In this way, the code is more performant, because the expression is cached, and arguably more clear, since you don't need to call the method with the argument in the html.
Upvotes: 4
Reputation: 421
If you like typescript, you can write it like this
import { Vue, Component } from 'vue-property-decorator';
@Component({name: 'test-component'})
export default class TestComponent extends Vue {
private message: string = 'Hello';
get reverse(): string {
return this.message.split('').reverse().join('');
}
}
And in your template
<div id="example">
<p> {{ message }} </p>
<p> {{ reverse }} </p>
</div>
Upvotes: 0
Reputation: 33186
Code between {{ }}
is interpreted as javascript, so you can pass the variable directly to the function:
<p> {{ reverse(message) }} </p>
Upvotes: 4