Utilizing external variables in Vue 2 Instance

I am currently developing a project using Laravel 5.5 & Vue 2.x. In this project, I need to define certain data in the frontend and then use it within the Vue instance:

Initially, I have my view or HTML file set up like this:

<fieldset class="form-group col-md">
    <label for="country" class="control-label">Country</label>
    <select class="form-control" name="country" id="country" v-model="selectedCountry" @change="selectCountry()">
        <option :value="null" :selected="selectedCountry">Select one</option>
        <option v-for="country in countries" :value="country.id">@{{ country.name }}</option>
    </select>
</fieldset>

<script>
    var formSelectedCountry = {{ isset($property) ? $property->country_id : "null" }};
    var formSelectedDepartment = {{ isset($property) ? $property->department_id : "null" }};
    var formSelectedLocation = {{ isset($property) ? $property->location_id : "null" }};
    var formSelectedZone = {{ isset($property) ? $property->zone_id : "null" }};
</script>

Everything works well with this setup. However, on other pages where formSelectedCountry (for example) is not defined, Vue seems to encounter issues.

In my app.js, I have the following:

data: {
    ...
    selectedCountry: formSelectedCountry,
    selectedDepartment: formSelectedDepartment,
    selectedLocation: formSelectedLocation,
    selectedZone:  formSelectedZone,
    ...
}

I've also attempted to pre-define these variables by adding the following lines:

formSelectedCountry: '',
formSelectedDepartment: '',
formSelectedLocation: '',
formSelectedZone: '',

Alternatively, there might be a way to set the data using something like

selectedCountry: (formSelectedCountry ? formSelectedCountry : null)
.

Your thoughts and suggestions would be greatly appreciated.

Answer №1

If you want to initialize certain variables using the created lifecycle hook, here is an example:

var formSelectedCountry = {{ isset($property) ? $property->country_id : "null" }};
var formSelectedDepartment = {{ isset($property) ? $property->department_id : "null" }};
var formSelectedLocation = {{ isset($property) ? $property->location_id : "null" }};
var formSelectedZone = {{ isset($property) ? $property->zone_id : "null" }};
new Vue({
 data: {
 ...
 selectedCountry: '',
 selectedDepartment: '',
 selectedLocation: '',
 selectedZone:  '',
 ...
 },
 created:function(){
   this.selectedCountry = formSelectedCountry;
   this.selectedDepartment= formSelectedDepartment;
   this.selectedLocation= formSelectedLocation;
   this.selectedZone= formSelectedZone;
 }
})

Check out this demo on JSFiddle

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

What is the best approach for choosing unquoted HTML attribute values?

I have a unique situation where I am dynamically appending a select element to a form from a hidden field, with escaped spaces in the element content. This is the hidden field content: <input type="hidden" id="field1" name="field1" value="<select i ...

The system is unable to retrieve the value of the property which is set as null

I'm trying to figure out how to store the input value of name_enter into the variable userName. However, every time I attempt this, I encounter the following console error: Uncaught TypeError: Cannot read property 'value' of null function ...

Obtaining IDs of Divs that have been Dragged into a Drop Zone upon Clicking a Button using JavaScript

I'm currently working on a solution to extract the ids of dragged divs once they have been placed in the drop zone. Each drag component is assigned an id ranging from drag1 through drag8, while the drop zone is labeled as div drop zone. Since there a ...

Exploring the magic of Laravel with Ajax and how to effectively utilize prevent

I am encountering an issue with adding and removing items from my cart using Ajax. After adding an item to the cart, the Ajax functionality works perfectly. However, when I attempt to remove an item from the list, it does not work with Ajax the first time. ...

The ngModel functionality struggles to accurately detect changes within arrays

The component model: private SomeArray = [{ key: "Initial" }]; User has the ability to dynamically add or remove items: addField() { this.SomeArray.push({ key: Math.random().toString() }); } removeField(index: number) { this.SomeArray.splice(ind ...

Tips for implementing the debounce function in CanJS DefineMap view-model method

I have been attempting to implement the lodash function _.debounce for a DefineMap view-model method in canjs. Even after trying to do this within the init method, I am having trouble with properly referencing 'this' inside the debounced function ...

The Backbone model destruction URL fails to include the model's ID when trying to delete

I'm facing an issue in my app where I need to delete a model from a collection using "this.model.destroy" in my view, but it triggers a 405 response and the response URL doesn't include the model's id. According to the Backbone documentation ...

Is it possible to remove content from a Content Editable container?

JSFiddle <div contenteditable="true"> <p>Trying out editing capabilities of this paragraph.</p> <figure> <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/ima ...

Exploring the effectiveness of utilizing Vue and Vuex for storing data within a filter component

Trying to get the hang of Vue and struggling with some basic concepts. Currently, I have a Vuex-based store where I fetch the USDEUR currency rate from an API every 15 seconds. Within my component, I have a fixed price in dollars that needs to be replaced ...

Implementing Conditional Value Assignment in JavaScript

When a specific id is received, I need to assign a value to my variable based on the condition that this id matches any of the ids in an array. For instance, consider the following array: { key: value, key: value, dir ...

Encountering an error of "undefined is not iterable, cannot read property Symbol(Symbol.iterator)"

While learning React through coding, I encountered an error (Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)). I am unsure where the problem lies. Any suggestions? When utilizing useEffect to activate setFiltere ...

The scroll-to-top button refuses to fade out

I am currently facing a challenge with my scroll to top button not functioning properly. It seems like there is an issue arising from another animation that I can't seem to pinpoint. Specifically, when the other animation is triggered at "scroll hits ...

Create line items using the quantity code as a reference

I need help implementing a feature that dynamically adds line items based on user input in a quantity text box. For example, if the user enters a quantity of 2, the page should display: Text line for item 1 Text line for item 2 Here is the code snippet ...

Are there JavaScript counterparts to the constant strings in Python?

In my search for a Javascript equivalent to the constant string ascii_lowercase 'abcdefghijklmnopqrstuvwxyz', I have come up empty-handed. However, I am more than willing to create it myself. Having found this feature useful in Python, I am curi ...

Issue: Request from a different origin blocked

I encountered an issue while working on a web project using the PlanGrid API. I am receiving a cross-domain request block error. var apiKey="API KEY"; var password="PASSWORD"; $.ajax({ url: "https://io.plangrid.com/projects", xhrFields: { ...

PHP - session expires upon page refresh

I'm in the process of creating a login system for my website and I've run into an issue with updating the navigation bar once a user has logged in. Every time I refresh the page, it seems like the session gets lost and the navigation bar doesn&ap ...

Best method for displaying a div using ASP.NET server controls

There is a concealed div containing ASP.NET server buttons. When I display the content of this div as a modal window on the page using JavaScript by copying innerHTML, the buttons do not trigger server events. Can anyone offer a solution to this issue? ...

What steps are involved in creating a default toolbar for a material picker in a React application?

Looking for assistance with customizing the toolbar for material picker (v3) by adding a title inside the dialog. I successfully implemented this in the KeyboardDatePicker following a helpful thread (https://github.com/mui-org/material-ui-pickers/issues/11 ...

Adding a list without a specific order into a paragraph with the help of jQuery

Working on a client-side class, I am in the process of changing an XHR request and getElementById function to a jQuery ajax request along with jQuery document manipulation. The task at hand is to display descriptions of items available from "Rob's Roc ...

Changing the Color of Material-UI Slider: A Step-by-Step Guide

Looking to update the color of Material UI Slider component I have attempted to adjust the CSS styling without success, followed by trying the solution provided in this issue and applying the following code, but the changes are not being reflected: getMu ...