Eldar Tailov
Eldar Tailov

Reputation: 59

How to pass computed function into v-bind and v-on?

I know it's simple example, but I'm new to Vue.

I'm sure that error is where I pointed. I'm trying to call function from computed method. There is no problem if write code straight to v:bind, but once I pass it throug func it gives me error. As well I know that from method functions call as func(), but I guess from computed they have another syntax.

  <body>
        <div class="container">
            <hr>
            <div class="sample">
            <input type="text" v-bind:value="name" v-on:input="name = $event.target.value">
            <hr>
            <h2>Hello, {{ name }}</h2>
            <input type="button" value="Click on it" v-on:click="addNumber()">
            <hr>
            <div v-for="num in numbers">
                {{ num }}
            </div>
            <input type="button" v-on:click="show" v-bind:title="btnText" > //I'M SURE ERROR IS HERE
            <h2 v-show="showH2">check hide</h2>
            </div>
        <div></div>
        <script>
            let sample = new Vue({
            el: '.sample',
            data: 
            {
                showH2: true,
                name: '12344',
                numbers: []
            },
            methods:
            {
                addNumber()
                {
                    let num = Math.floor(Math.random() * 11) - 5;
                    this.numbers.push(num);
                }
            },
            computed: 
            {
                btnText()
                {
                    return this.showH2 ? 'Hide' : 'Show';
                },
                sum()
                {
                    let sum = 0;
                    this.numbers.forEach((el) => sum += el);
                    return sum;
                },
                show()
                {
                    this.showH2 = !this.showH2;
                }
            }
            });
        </script>
    </body>
    </html>

Upvotes: 0

Views: 356

Answers (1)

Manoj
Manoj

Reputation: 831

You are perfectly correct when you say- "There is no problem if write code straight to v:bind, but once I pass it through func it gives me error". This is because You don't call a computed and it doesn't accept any parameters. You reference a computed property just like you would a data property. Whereas a method is just a function bound to the Vue instance. It will only be evaluated when you explicitly call it. So if you shift show in methods it will work. vue doc

Upvotes: 2

Related Questions