Unable to confirm form validation with Vue

Recently, I started working with Vue and encountered a problem while running the code below. The error message "

ReferenceError: $vAddress is not defined
" keeps popping up. Despite my efforts to search for solutions online, I couldn't find any that addressed my specific issue.

<form class="form-horizontal" role="form">
    <validator name="vAddress">
        <div :class="{'has-error': $vAddress.firstname.required}" class="form-group">
            <label for="firstname" class="control-label">First Name</label>
            <div class="text-left">
                <input
                type="text"
                class="form-control"
                name="firstname"
                v-validate:firstname="['required']"
                v-model="newAddress.firstname">
                <small v-if="$vAddress.firstname.required" class="help-block text-danger">The first name is required</small>
            </div>
        </div>
        <div ...>
    </validator>
</form>

<script type="text/javascript">
    (function() {
      var account = new Vue({
        el: '#checkout-content',
        data: {
          user: {!! json_encode(Auth::user()) !!},
          billingAddress: {!! json_encode($billing_address) !!},
          shippingAddress: {!! json_encode($shipping_address) !!},
          newAddress: {},
          activeAddress: {
            shipping: '',
            billing: '',
          },
          alert: ""
        },
        computed:{
            shipping: function(){
                return !(typeof this.activeAddress.billing == 'undefined' || typeof this.activeAddress.shipping == 'undefined');
            }       

        },
        filters: {
          isExist: function(value){
            if (typeof value === 'undefined') return ' ';
            return value;
          }
        },
        methods: {
          // save new address
          saveAddress: function() {
              // save new address
              if (typeof this.newAddress.key == 'undefined') {
                  if (typeof this.user.data.address == 'undefined')
                      this.$set('user.data.address', []);
                  if (this.newAddress.defaultAddress){
                      this.clearDefaultAddress();
                  }
                  this.user.data.address.push(this.newAddress);
              }else{
                  var key = this.newAddress.key;
                  if (this.newAddress.defaultAddress){
                      this.clearDefaultAddress();
                  }
                  this.user.data.address[key] = this.newAddress;
              }
              this.$http.post("{{ route('account-addresses') }}", {
                  address:this.user.data.address
              }).then((response) => {
                  this.user.data.address = response.body.user.data.address;
                  $.notify({
                      message: response.body.message
                  },{
                   type: 'success',
                   animate: {
                    enter: 'animated fadeInDown',
                    exit: 'animated fadeOutUp'
                   },
                });
                // reset values
                $('#new-address').modal('hide');
                this.newAddress = '';
              }, (response) => { });
          },
          // update address
          updateAddress: function(address, index) {
              this.newAddress = address;
              this.newAddress.key = index;
              this.user.data.address[index] = '';
              $('#new-address').modal('show');
          },
          clearDefaultAddress: function(){
              // clear all default values to none
              for (var i = 0; i < this.user.data.address.length; i++) {
                  this.user.data.address[i].defaultAddress = 0;
              }
          },
          shippingProccess: function(){
            if(typeof this.activeAddress.billing == 'undefined' || typeof this.activeAddress.shipping == 'undefined') {
                this.alert.error = true;
            }else{
                this.alert.loading = true;
                this.$http.post('{{ url('checkout/add_address') }}', {
                    billing: this.activeAddress.billing,
                    shipping: this.activeAddress.shipping
                }).then((response) => {
                    // PROSSED TO NEXT STEP
                    window.location = '{{ url('checkout/shipping') }}'; 
                }, (response) => {
                });
            }
          }
        },
        ready() {
          // set default address
            this.activeAddress.billing = this.billingAddress.defaultAddress
            this.activeAddress.shipping = this.shippingAddress.defaultAddress
        }
     });
   })();
</script>

Questions:

  1. What seems to be causing the issue?
  2. Any suggestions on how to resolve this error?

Note:

The version of Vue I am using is 2.6.10.

Answer №1

When vue is unable to locate $vAddress in the data scope,

You must define and place $vAddress within your vue data initiator, for example, as shown below:

   ... 
   data: {
      user: {!! json_encode(Auth::user()) !!},
      vAddress: {!! json_encode($vAddress) !!}
      billingAddress: {!! json_encode($billing_address) !!},
      shippingAddress: {!! json_encode($shipping_address) !!},
      newAddress: {},
      activeAddress: {
        shipping: '',
        billing: '',
      },
      alert: ""
    },
    ...

After this adjustment, you should be able to use vAddress in v-if conditions.

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

Using b-icon with the <td> tag in VueJS

I am looking to incorporate HTML content within a table data element using VueJS. Below is an illustration of my situation: <template> <div> <div v-if="someObject.properties" style="margin-top: 20px;" class="table-responsi ...

Add a sub-modal window inside a separate container

Is there a way to attach this modal to an external div? The current setup involves nesting it within a container that has a fixed height. I'm looking to move it outside of that container. Here is the JavaScript code for the modal: client.fetchQuery ...

Updating variable value in a Javascript function

I'm currently working on a signup page and I need to verify if an email address already exists in the database. var emailnum = getEmailCount(`select * from contactinfo where email='${email}'`); console.log(emailnum); // Output shows ...

"Is it possible to make a JSON API call in Node.js before exiting with a SIGINT

In my attempt to configure certain variables and make an API call using the request module before exiting the program, I encountered issues where the function was not being properly executed due to the presence of both SIGINT and exit signals: const reque ...

Using Vue.js to increment a value in an array every time a new row is added

In Vue.js, I am attempting to increment an array value when adding a new row. However, I encounter the following error message: You may have an infinite update loop in a component render function. The JavaScript logic looks like this: new Vue({ el: ...

Encountering a Cypress testing issue linked to webpack. Feeling unsure about the next steps to address it

https://i.sstatic.net/z6bmW.png I encountered an error while attempting to run a test file that I created. The default tests run smoothly, but the error only occurs with the file I created. import {cypress as cy} from "cypress" describe('T ...

Issue with integrating Razorpay into a Node.js Express application

I am currently working on setting up a checkout page using nodejs and express with Razorpay as the payment gateway. The issue arises when trying to run the checkout() function by clicking the "Checkout" button within my shopping-cart.hbs file. Despite havi ...

Can conditional statements be utilized within a React component?

Using Material UI, the CardHeader component represents the top part of a post. If the post is created by the user (isUser = true), I would like to display two buttons on the post. Is this achievable? <CardHeader avatar={ <Avatar sx={{ ...

I'm having trouble sending a string to a WCF service using jQuery AJAX. What's preventing me from sending strings of numbers?

Something strange is happening with my web service when using jquery ajax - I can only pass strings containing numbers. This was never an issue before as I would always just pass IDs to my wcf service. But now that I'm trying something more complex, I ...

What is the best way to reload DataTables using an ajax/error callback?

In my code, I am customizing the default settings of DataTables like this: $.extend(true, $.fn.dataTable.defaults, { lengthChange: false, deferRender: true, displayLength: 25, stateSave: false, serverSide: true, processing: true, ...

Switch between different react components

When a component is opened, I want all other components to close. Whenever they are clicked, they will display a list. class ParentComponent extends Component{ constructor(props){ super(props) this.state= {...} } render(){ return( ...

Conditional ngOptions in AngularJS allows you to dynamically update the options

Currently, I am working with a select box that iterates through an array of departments to identify eligible parent departments. <select class="editSelectBox" ng-model="dept.parentDepartment" ng-options="dept as dept.name for dept in depts track by de ...

Attaching a function to the "onselect" event that manages the character limit within an input text field

I have been developing a function to restrict the number of characters a user can enter into a text field. Here's what I have so far: $.fn.restringLength = function (id, maxLen) { $(id).keypress(function(e){ var kCode = ...

Exclude a variety of keys using wildcards or regex when conducting comparisons

How can I exclude certain properties in a JSON object that contain specific characters? var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""} var obj2 = {name: "Maria", age: 17, creation: "13-02- ...

What is the best method for storing a Google Analytics object in a $_SESSION variable when transitioning between PHP scripts to avoid encountering a non-object error

Currently in the process of developing a web application that integrates with the Google Analytics API, however encountering challenges when it comes to implementation. The user is given the option to choose their profile from three interconnected drop-do ...

How can I obtain the current state of HTML checkboxes from a local JSON file?

I have an HTML table with checkboxes, and I want to save the state of each checkbox in a local .JSON file instead of using localStorage. When the page reloads, I want it to automatically load the saved JSON file to retrieve the previously configured checkb ...

React-modal triggers the file-explorer upon exiting the dropzone

Within my project, I have implemented a button that triggers a modal to appear on mouse-over. This button is nested inside a dropzone element. https://i.sstatic.net/95dxy.png The issue arises when I exit the modal by clicking (not exiting with the escape ...

Testing React components with Jest by mocking unnecessary components

Consider a scenario where we have the Page component defined as: const Page = () => <> <Topbar /> <Drawer /> <Content /> </> When writing an integration test to check interactions within the Drawer and Con ...

Tips for adding color to the <td> element in an ejs file using nodeJS

I am looking to incorporate a color into my .ejs file. Here is the code snippet I am working with: <% resultList.forEach(function(item, index){ %> <tr> <td><%= item.function %></td> <td><%= item.value %>< ...

selecting a div element with a label using the nth-child property

I recently discovered the CSS3 :nth-child() Selector and decided to create a sample Here is the HTML snippet: <body> <div> <label>dsdf</label></div> <div>seconddiv</div> </body> And here's the CSS par ...