A step-by-step guide to moving Vue .prototype to its own file

I have a couple of functions that I need to add to Vue's .prototype. However, I don't want to clutter up the main.js file. I attempted to move the prototypes like this:

//main.js
import "./vue-extensions/prototypes";

//prototypes.js
import Vue from "vue";
export default new Vue.prototype({
    $appName = "myName",
});

However, when I tried this approach, I encountered an error: `ERROR Failed to compile with 1 error 6:35:11 PM error in ./src/vue-extensions/prototypes.js

Syntax Error: D:\Projects\FrontEnd\gta\src\vue-extensions\prototypes.js: Unexpected token (3:19)

1 | import Vue from "vue"; 2 | export default new Vue.prototype({

3 | $appName = "myName",

@ ./src/main.js 14:0-37 @ multi (webpack)-dev-server/client?http://192.168.3.200:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js`

Answer №1

Oh no, that certainly is a syntax error - trying to assign a statement within an object literal.

Avoid instantiating anything and refrain from using new . Also, don't export anything for main imports. Simply include the code that alters the prototype object in the module and nothing more:

//prototypes.js
import Vue from "vue";

Vue.prototype.$appName = "myName";
Vue.prototype.$assetsResolution = document.body.clientWidth * devicePixelRatio <= 1920 && document.body.clientHeight * devicePixelRatio <= 1080 ? 1080: 2160;

An alternative approach, which clarifies the process (as extending prototype objects you do not own is generally discouraged), would be to still perform the assignment in main.js but define all values in a separate module:

//main.js
import prototypeExtensions from "./vue-extensions/prototypes";

Object.assign(Vue.prototype, prototypeExtensions);
//prototypes.js
import Vue from "vue";

export default {
    $appName: "myName",
    $assetsResolution: document.body.clientWidth * devicePixelRatio <= 1920 && document.body.clientHeight * devicePixelRatio <= 1080 ? 1080: 2160
};

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

The order in which JavaScript files are loaded is critical, especially when dealing with external

After experiencing issues with my script not working because it was loaded before jQuery by the client (a necessity), I am seeking a solution. My challenge lies in ensuring that my code waits for jQuery to load before execution, especially when dealing wi ...

Transform an array of object's designated key values into a string that is separated by commas

Is there a way to convert specific key values of an object into a comma-separated string? I have been able to do this with arrays, but my current challenge is that my data is an array of objects. I want to convert each 'id' value into an array of ...

Cloud Firestore trigger fails to activate Cloud function

I am facing an issue with triggering a Cloud Function using the Cloud Firestore trigger. The function is supposed to perform a full export of my sub collection 'reviews' every time a new document is added to it. Despite deploying the function suc ...

What steps can you take to address Git conflicts within the yarn.lock file?

When numerous branches in a Git project make changes to dependencies and use Yarn, conflicts may arise in the yarn.lock file. Instead of deleting and recreating the yarn.lock file, which could lead to unintended package upgrades, what is the most efficie ...

Step-by-step guide on accessing and displaying a disc file within a webix application

I am a beginner in webix development and struggling to find documentation or help for my current issue. Within my webix application, I am trying to create a button (let's call it 'View Report') that when clicked will open a file from my loc ...

Displaying a table in Chrome/Firefox with a mouseover feature

Hovering over the rows of this table triggers a display of descriptions. html: <tr title="{{transaction.submissionLog}}" class="mastertooltip">... JavaScript: $('.masterTooltip').hover(function(){ // Hover functionality ...

Display the precise outcome for each division following a successful AJAX callback

I’m facing a challenge in getting individual results for each item after a successful AJAX callback. Currently, I am able to retrieve results, but when there are multiple items, all displayed results are being added to each div instead of just the corres ...

Changing the value of a ref in Vue 3 within a function

I need to change the value of 'reset' from true to false when a file is uploaded. Even though 'reset' is externally set to true, it should be changed to false during file upload process. How can this be achieved? <template> rese ...

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

Axios issue: Cookies are not being transmitted

I have encountered an issue with a form built on Nuxt/vuejs and the backend side on django where CSRF protection is enabled. The API call now requires two things: X-CSRFToken as a header and csrftoken as a Cookie. I tested the API using Postman and it work ...

Unable to invoke functions in the child window

In my Vue page, I have a script that opens a child window using the code snippet below: this.presentation = window.open( this.$router.resolve({name:'presentation'}).href, 'child window', 'width=auto,height=auto' ) ...

Leverage the power of Signal R through React with aspnet/signalr integration

I found a helpful resource for incorporating SignalR into react, which you can check out here. However, it seems that the code provided does not align with current standards. The @aspnet/signalr-client has been marked as obsolete and now we are required t ...

Determine the presence of a JSON object within a file using JavaScript

Currently, I am developing a mobile app using react-native and have been facing challenges implementing error checking. To store data retrieved from an API in JSON format, I am employing redux along with thunk. At times, the search results yield a JSON res ...

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...

Retrieving and storing successful response data in Angular JS using the $http service caching

My dataFactory is set up to retrieve posts in a simple manner: dataFactory.getPosts = function () { if (this.httpPostsData == null) { this.httpPostsData = $http.get("http://localhost/matImms/wp-json/posts?type=journey&filter[posts_per_page ...

An Axios interceptor will consistently fulfill a promise

Is it possible to intercept an axios post call in Vue? To start, we need to create Axios in a file called axios.js: import Vue from 'vue' import axios from 'axios' const axiosInstance = axios.create({ baseURL: `http://localhost:808 ...

Can you explain the functionality of the DataTable drawCallback feature?

I'm currently facing an issue where CSS is not being applied to all cells in a DataTable based on their values when using drawCallback(). While the CSS gets applied to some cells, it's inconsistent. You can check out the JsFiddle of my problem he ...

The event is being triggered on two separate occasions

Hey there! I'm trying to bind the onclick event to both a parent and child element using the same method. However, I'm running into an issue where the event is being fired twice. Any suggestions on how to prevent this from happening? <div id= ...

Enhancing the default functionality of React.FC within Next.js

Currently, I am working on a tutorial in Nextjs that employs the code snippet below in JavaScript. However, I am planning to transition it to TypeScript. Since I am relatively new to TypeScript, I have attempted various solutions from different sources but ...

Utilize JQuery to inject both standard HTML elements and safely rendered escaped HTML onto a webpage

After storing some data in firebase that can be retrieved on the client side, I use JQuery to add it to the HTML. Although the process of prepending the data to the DOM element is straightforward, there is a security concern as raw code can make the applic ...