Unable to add new Instance Properties in Vue.js within a Laravel project

I am attempting to develop a localization property similar to __('text') in Laravel blade template. I have set up a global window variable that contains all required data under the name window.i18n

Below is my resourses/js/app.js file:

require('./bootstrap');

window.Vue = require('vue');

// I am trying to create new instance properties here
import _ from 'lodash'
window.Vue.prototype.__ = str => _.get(window.i18n, str)

Vue.component('autocomplete',require('./components/SearchComponent.vue').default);

const app = new Vue({
    el: '#app',
});

Here is the script part of my /components/SearchComponent.vue file:

<script>
 export default{
    props: [
        'categories'
    ],
    data(){
        return {
            query: '',
            results: [],
            categoryText: __('text.save'), // Trying to use __() property here
            categoryId: 0
        }
    },
    methods: {
    autoComplete() {
        this.results = [];
        if(this.query.length > 2){
            axios.get('/posts/search',{params: {query: this.query, category_id: this.categoryId}}).then(response => {
                this.results = response.data;
                this.categoryText = "Избери";
                this.categoryId = 0;
            });
        }
    },
    categoryChange(e) {
        this.categoryText = e.target.text;
        var id = event.target.getAttribute('data-category-id');
        this.categoryId = id;
    },
    mounted: function () {
        console.log(this.categories);
    }
    }
 }
</script>

The error message I encountered is:

app.js:38639 [Vue warn]: Error in data(): "ReferenceError: __ is not defined"

Can't figure out what I might be missing.

Answer №1

By adding __ to the Vue.prototype, you are creating an instance property. To access these properties, simply use this within the data() method:

export default {
  data() {
    return {         👇
      categoryText: this.__('text.save')
    }
  }
}

Another approach is to make __ global by attaching it directly to window. This allows your current code to function properly:

window.__ = str => _.get(window.i18n, str)

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

Can you explain the process of utilizing WebdriverIO (wdio) to determine the frequency of an element's occurrence?

Currently, I am working on creating an interaction test to validate my javascript code using WebdriverIO (wdio). The specific functionality I am looking to test involves deleting a node and verifying that the number of times a selector appears has decreas ...

My Jquery "animate" is only triggered once instead of on each function call. What could be causing this issue?

I have set my navigation to dock at a specific document height on the top of the viewport, and when it docks, it should display a dropdown animation. $(document).scroll(function(){ var x = $(window).scrollTop(); if(x>=700){ $("header ...

The react-xml-parser package is asking for Babel version "^7.0.0-0", however it was instead loaded with version "6.26.3". I have already attempted all available solutions to resolve this issue

I have attempted numerous solutions from the Github community regarding this issue, but unfortunately none have worked for me. /node_modules/react-xml-parser/dist/bundle.js: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you ha ...

Commit to persevering until you achieve success

I'm currently working with native node.js Promises and did not find any useful information in this thread. Essentially, I am dealing with a function that looks like this: var foo = foo (resolve, reject) { return obj .doA() .doB() ...

Error: Trying to assign a value to a null property

I am facing an issue while trying to dynamically create "iframe's textarea" and insert the value of a variable. Unfortunately, I keep encountering an error. Any suggestions on how to resolve this problem? P.S: Using Google Chrome as the browser ...

Unexplained disappearance of div element in Vue Router's Navbar

I have been working on integrating a Vue Router into my navbar and everything seemed to be going well. You can check out the code here. The navigation menu I created works perfectly, allowing users to navigate between the home template and about template w ...

"Encountering an issue with AngularJS where the selected ng-model value is

I'm utilizing plain options for the select tag because I only need to display a few options when they meet a certain condition. In order to perform other operations, I require the value of the selected dropdown in the controller. However, the issue is ...

Tips on accessing data from child components within a parent method in Vue.js

I am working on a project that involves a dynamic list of custom input field components. When a button is clicked in my parent Vue component, I need to create a method that will loop through all the components in the list to retrieve their values. Here is ...

Can you explain the meaning of EPS in the THREE.OrbitControl function?

The this.update method within the THREE.OrbitControl script contains a private variable called EPS, which is used to adjust the phi angle. The following code snippet demonstrates how it restricts phi to be between EPS and PI-EPS: // restrict phi to be bet ...

Error: scrollreveal JavaScript is not properly defined

Desperately seeking guidance on a particular code snippet... window.sr = ScrollReveal({ reset: true }); sr.reveal('.whitecircle, .circleStatsItemBox, .circleStat', { duration: 200 }); function circle_program() { var divElement = $(&apo ...

Handling a JSON array error when working with a JSON string field

Attempting to create a JSONArray object with nested arrays and json strings, specifically looking at the "res" field. [{ "time": 123813213, "value": [{ "name": "task", "res": "{\"taskName\" : \"NAME\", \"ta ...

Retrieve the specific file path of a dependency within the node_modules directory

Can you help me find the exact path of a dependency within a specific node_modules package? Here's an example setup: |- node_modules/ |- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4a4b5b7bfb5b3b1f9b594e6fae5fae4"& ...

Loading images lazily using knockout.js

I have been working on implementing lazy loading for images using knockoutjs binding. I previously successfully implemented lazy loading without the knockoutjs framework, but I am unsure of how to achieve this with knockoutjs binding. Below is my HTML code ...

Creating a simulation of a JavaScript callback within a C# host program

Currently, I am in the process of developing a c# application with an embedded web browser control. In this project, I'm facing a challenge where I need to call a C# method from JavaScript and pass a JavaScript callback using the dynamic technique exp ...

Issue: The specific module is unable to be located, specifically on the Heroku platform

While my application performs well locally and on a Travis CI build server, it encounters issues when deployed on Heroku. The error message Error: Cannot find module is displayed, leading to app crashes. Here are some details about the npm module: It r ...

Exploring the depths of time travel in Redux without the aid of developer

Has anyone successfully achieved time traveling capabilities with Redux core? It seems that this feature is limited to the devtools and not advised for production use. I had planned on implementing Redux in a multiplayer game to assist with managing clie ...

Using a wildcard (*) to select elements with JQuery

I'm just starting to learn about JQuery and could use some help. I want to select multiple elements but I only know part of their Ids: for example: <div id="element32422455">Some content</div> <div id="element68475124">Some content& ...

Using jQuery to toggle the visibility of HTML elements

Hi there, I am trying to create an interactive HTML sidebar where each section shows its respective posts when clicked. However, I am facing issues as the content keeps hiding continuously. <div class="col-md-3"> <div class="list-grou ...

Tips for altering the color of string outputs

Can you help me modify a function to display different colors based on the output? For instance, I want it to show in orange if the result is too low, and in red if it indicates obesity. bmiCalculation() { var weight = parseInt(this.currentWeight); ...

Utilizing URL Parameters in MEANJS

I'm currently testing my app on localhost:3000/#!/, and am encountering difficulties in retrieving URL parameters for use with Express. I have set up a new server routing file that includes the following: admin.server.routes.js 'use strict&apos ...