Tips for integrating a computed function with v-bind and v-on in Vue.js

Although it may seem like a simple example, I am just starting to learn Vue.

I believe the error is occurring where I have indicated. I am attempting to call a function from a computed method. There doesn't seem to be an issue when writing the code directly in v:bind, but once I pass it through a function, it gives me an error. I understand that functions are called as func() from method, but I suspect there might be a different syntax when calling them from computed.

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

Answer №1

When you mention that "There is no problem if write code straight to v:bind, but once I pass it through func it gives me error", you are absolutely correct. This happens because when passing the code through a function, you are not calling a computed property and it doesn't accept any parameters. In this case, you reference a computed property just like you would a data property. On the other hand, a method is essentially a function bound to the Vue instance, and it will only be evaluated when explicitly called. Therefore, in order for it to work properly, you should shift 'show' to methods. vue doc

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoid having logs displayed on the server end when utilizing console.log commands

Being new to JavaScript and Node.js, I am attempting to have my application output logs on the server side. getUser.onclick = function () { console.log('Server running at http://127.0.0.1:1337/'); var req = new XMLHttpRequest(); r ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

What causes nodejs to exit prematurely without running all the code?

When running the code provided, it randomly prints "DONE" or not. Can you explain why this happens? How can I ensure that it always reaches the console.log("DONE"); line every time? const {Worker, isMainThread, parentPort} = require('node:worker_threa ...

Please disable zoom functionality on the website specifically for Android devices

Is there a way to disable the zoom feature on our website specifically for Android phones/devices without affecting iPhones? Perhaps targeting the Chrome browser on Android would be sufficient, but we should also verify the mobile screen size. ...

Guide to displaying options in the Vue material select box even when the default value is blank

I have implemented the material design framework vuematerial with vue.js. In traditional HTML, a selection box looks like this: <select> <option value="">You should initially see this</option> <option value="1">One</o ...

Nuxt Vuex global state update does not cause v-for loop components to re-render

I am struggling to effectively use Vuex global state with re-rendering child components in Vue.js. The global state is being mutated, but the data does not update in the v-for loop. Initially, all data is rendered correctly. However, when new data is intr ...

Top method for enhancing outside libraries in AngularJs

Currently, I am utilizing the angular bootstrap ui third party library as a dependency in my angular application. One question that is on my mind is what would be the most effective method to enhance the functionality of directives and controllers within t ...

The model `user` does not have a primary key attribute specified. It is required for all models to have a primary key attribute defined

I have defined a waterline model below: var Waterline = require('Waterline'); var bcrypt = require('bcrypt'); var User = Waterline.Collection.extend({ identity: 'user', datastore: 'myMongo', autoPK: false, attribut ...

The Angular 5 keyup event is being triggered twice

My app is incredibly simple, just a basic hello world. To enhance its appearance, I incorporated bootstrap for the design and ng-bootstrap for the components. Within one of my TS files, you will find the following code: showMeTheKey(event: KeyboardEvent) ...

Ways to create a class method to increase a counter?

Can someone help me figure out how to create a custom function or class from the code below? I want to be able to import this module in order to easily increment a count whenever an event occurs in my application. I'm tired of having to manually inpu ...

Modify the values in a textbox using JavaScript to suit your needs

unusual issue: I'm encountering a strange bug with my form. I have an ajax datepicker attached to a text box, but when I submit the form, all values are received except for those from the datepicker checkboxes. Why is the .Text property empty for th ...

Creating a dynamic multi-series line chart in D3 version 4 that incorporates data points with matching colors to their respective lines

In my attempt to enhance a multi-series line chart with D3 V4 in Angular-cli, I have encountered a challenge. Below is the code snippet of what I have been working on. var lookBookData = z.domain().map(function (name) { return { name: name, ...

Why is the radio button not chosen in the ns-popover popup? The radio button is only selected in the popup of the last column

In my Angular controller, I am trying to set the radio model but it is only appearing in the last column popup of the table. The ns-popover is displayed when clicking on a table column. Here is the Angular Code: var app = angular.module('app', ...

Middleware for enabling the Cross-Origin Resource Sharing (CORS) functionality to efficiently manage preflight

My CORS configuration is set up globally to handle credentials like this: app.use(cors({ origin: 'https://example.com', credentials: true })) However, there are certain routes where I need to allow OPTIONS requests. Following the documentation, ...

Instructions on changing the color and font weight of an asterisk within a Textfield using Material UI

Is there a way to style the asterisk in red and bold within a Textfield using material UI? I have a placeholder text without a label, as my label is null or empty. I would like to make the placeholder star RED. Is this possible? Here is the code snippet: h ...

Where is the ideal location to store non-component data properties in Vue.js?

Currently, I am in the midst of a Vue.js project where components are predominantly used. However, there are moments when I simply need to incorporate some Vue.js syntax without creating an entire component. Since I am not utilizing the render function as ...

Stop the Text Table from being highlighted

My webpage includes a dynamic table where users can select multiple rows. jQuery events and CSS are utilized to provide visual feedback when a row is selected. However, pressing the shift key sometimes causes text to become highlighted, which is not idea ...

Angular 4: The Authguard (canActivate) is failing to effectively block the URL, causing the app to break and preventing access to all resources. Surprisingly, no errors are being

I have created an authguard, but it seems to not be blocking the route when the user is logged out. The authentication workflow in the app works fine, as I am using traditional sessions on the backend database. I have also verified the state of the auth se ...

How can you substitute sections of a sentence with an array of strings?

I have a specific sentence that needs formatting: span class="searchmatch" Program /span, programme, programmer, or span class="searchmatch" programming /span may refer to: span class="searchmatch" Program /span management, th ...

The act of initiating a click on a radio button involves evaluating conditions prior to toggling

Apologies for the slightly ambiguous title, let me provide a clearer explanation. I have created a codepen to demonstrate an issue that I am facing. You can view it here. In my codepen, I have two toggle buttons labeled "Male" and "Female" for simplicity. ...