Using an external script to modify or call a Vue.js method

My Vue app is constructed using Webpack and includes a few basic computed properties, such as calculating the sum amount from input values. However, I now require the capability to replace the summation function with one stored in a separate file that is not part of the current assembly. Additionally, I need to be able to incorporate buttons and other functions, like subtraction, multiplication, and division based on flags set in the external file. How should I best go about implementing this? Any suggestions?

Thank you

Answer №1

It can be beneficial to keep your functions separate from your .vue components for a cleaner code structure. By creating pure components and exporting functions from external files, you allow your .vue components to simply import them. However, this approach is subjective and may not suit every development style.

The example below demonstrates how easy it is to integrate external functions into Vue components (or instances):

const sumFunction = (a, b) => {
  return a + b
}

new Vue({
  el: "#app",
  computed: {
    result() {
      return sumFunction(Number(this.a), Number(this.b))
    }
  },
  data() {
    return {
      a: 0,
      b: 0
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="number" v-model="a" /><br />
  <input type="number" v-model="b" /><br /> a + b = {{result}}
</div>

Your project structure could resemble the following:

externalFunction.js:

export const sumFunction = (a, b) => {
  return a + b
}

sumTemplate.vue:

<template>
  <div>
    <input type="number" v-model="a" /><br />
    <input type="number" v-model="b" /><br />
    a + b = {{result}}
  </div>
</template>
<script>
import { sumFunction } from "@externalFunction"

export default {
  computed: {
    result() {
      return sumFunction(Number(this.a), Number(this.b))
    }
  },
  data() {
    return {
      a: 0,
      b: 0
    }
  }
}
</script>

It's important to note that in this setup, unit tests play a crucial role. It's essential to monitor the inputs and outputs of your functions to prevent any component failures when making changes.

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

Achieving the extraction of a particular string from an HTML element using JavaScript

<input id="WD01B3" ct="CB" lsdata="{2:'WD01B4',4:'Any',20:'\x7b\x22WDA_TYPE\x22\x3a\x22DROPDOWN_BY_KEY\x22,\x22WDA_ID\x22\x3a\x22ABCA950297D2C0C432BAB9BB ...

Utilizing the Power of AJAX in Combination with an Event Loop

I have a function that is supposed to make AJAX requests with an event loop while taking 9 inputs at the top and querying them from a database. Currently, it only logs to the console but will eventually perform more actions. However, I am encountering an ...

Utilize the power of Wikitude within an Angular 2 application

I am currently working on integrating Wikitude Architect View in Angular 2 by referring to the code at this link. My goal is to implement this code in an Angular 2 compatible way. import * as app from 'application'; import * as platform from & ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...

What is the best way to set the first option in a mat-select to be

My approach to date selection involves using 3 mat-select components for day, month, and year. You can view a demo of this setup here. In an attempt to improve the code, I decided to set the initial options as null by modifying the following lines: allDat ...

Timeout during the beforeLoad event

I am currently working on writing some ExtJS 4 script and have come across the following code: var companyStoreModel = Ext.create('Ext.data.Store', { model: 'CompanyDataModel', proxy: { type: 'ajax&apos ...

Ways to distinguish between two div elements that have scroll bars and those that do not

I created a div with CSS styling. .comment-list { margin: 20px 0; max-height: 100px; min-height: 100px; overflow-y: scroll; width: 100%; background-color:#000; } Here is the HTML code for the div: <div class="comment-list"> </div> When the ...

Analyzing two strings as dates within Selenium

Currently, I am utilizing <tr> <td>storeEval</td> <td>var d=new Date(); d.getDate()+'-'+((d.getMonth()+1)) +'-'+d.getFullYear();</td> <td>date2</td> </tr> <tr> ...

The element fails to show up when the button is clicked after receiving data from the API

My main goal is to retrieve data from a Weather API upon button click. Once the data is fetched, I want it to be displayed inside a component called Weather on the screen. Currently, I am successfully fetching the data but the Weather component is not disp ...

I encountered an issue in Vue where the image source didn't display

As I was working on my code, I created a component that contains a slot. I tried to pass the image URL into an <img /> tag using v-bind:src, but unfortunately, the image did not show up on the document and there were no errors in the console. <MyC ...

The behavior of Quasar's q-drawer is quite unpredictable

Having made the transition from Vue.js 2 with Vuetify to Vue.js 3 with Quasar due to Vuetify not officially supporting Vue.js 3 yet, I am utilizing q-drawer and its mini property. This allows me to toggle between the mini state and the normal expanded stat ...

Having trouble with the CSS `not` selector?

Below is the code snippet I experimented with XHTML <div> <span>Span1</span> <span>Span12</span> <span>Span13</span> </div> <div> <span>Span1</span> <span> ...

Looking to test form submissions in React using Jest and Enzyme? Keep running into the error "Cannot read property 'preventDefault' of undefined"?

Currently, I am developing a test to validate whether the error Notification component is displayed when the login form is submitted without any data. describe('User signin', () => { it('should fail if no credentials are provided&apos ...

"Enhance input functionality by updating the value of the text input or resizing the textbox

I've been facing a challenge with updating the value of my input type=text or textbox control text value using jQuery $(window).resize(function(){});. I am aware that the event is triggered because an alert pops up when I resize the browser. Additiona ...

How can we manage a discovered item in Promise and Recursion scenarios without relying on a callback function?

I need to iterate asynchronously and recursively over a folder hierarchy on the server. When a file is found, I want to call a custom method. Here's my current code structure: searchFile(root, handleFile); // recursively loop through folders and ha ...

Using Flask to pass variable data from one route to another in Python using the `url

I am facing an issue with sending a variable value to Python from Flask HTML/JS via url_for(). Here's my Python code: @app.route('/video_feed/<device>') def video_feed(device): # return the response generated along with the speci ...

What is the process for invoking a server-side C# method from AJAX while transmitting parameters to the function using CommandArgument?

My C# method is responsible for saving data to a SQL Server. It is called from an Onlick event, passing parameters using CommandArgument. Here is an example: <asp:LinkButton runat="server" onClick="save" CommandArgument='<%# Eval("post_id").ToS ...

Dealing with illegal characters, such as the notorious £ symbol, in JSON data within a JQuery

I'm encountering an issue with a textarea and the handling of special symbols. Specifically, when I use $('#mytextarea').val() to retrieve text that contains '£', I end up seeing the black diamond with a question mark inside it. T ...

What is the method to include a class in the "template" tag within vue?

Can someone please advise on how to attach a class to the "template" tag in Vue? <template #popover class: templateClass // Wishing to include a class here, is it feasible? > <router-link v-close-popover to="/somewhere" ...

Despite using vue cli3, why am I unable to view the changes I've made to my configureWebpack settings?

Starting out with Vue cli 3. I've set up a vue.config.js file as follows... // vue.config.js var path = require('path'); module.exports = { baseUrl: process.env.NODE_ENV === 'production' ? '/production-sub-path/' ...