Transform a global JavaScript function into a global Vue.js function, compatible with the Vue Laravel framework

My JavaScript function displays a color border when required and changes the color if anything is inputted. It works fine in plain JavaScript but not in Vue.

I need to use this function in Vue, on any place or component.

app.js

$('.req' ).on('keyup', function() {
  let val = this.value
  val = $.trim(val)
  if(val==""){
    $(this).removeClass('valid');
  }else{
    $(this).addClass('valid');
  }
});

$('.req').change(function() {
  let val = this.value
  val = $.trim(val)
  if(val==""){
    $(this).removeClass('valid');
  }else{
    $(this).addClass('valid');
  }
})

Anyplace.blade.php

<form>
    <input type="text"  class="req form-control " name="last_name">
</form>

app.css

.valid{
    border-left: 2px solid #9cff2b !important;
}
.req{
    border-left: 2px solid red;
}

component-example.vue

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">papa</div>

                    <div class="card-body">
                        papa. esto viene del hijo {{ messaje }}
                        <br>
                        <input type="text" v-model="modelo" class="req ">
                    </div>
                </div>
                <hijo :numero=modelo  @verInfo="recibirpapa" > </hijo>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        mounted() {
            console.log('Component papa.')
        },
        data(){
                return{
                    modelo:"",
                    messaje:''
                }
        },methods:{
                recibirpapa(valor){
                    this.messaje = valor;
                }
        },
    }
</script>

Answer №1

You may want to give this code a try: insert

<req-input></req-input>
wherever desired.

Vue.component('req-input', {
    template: '#req-input-template',
  props: {
    value: {
        type: [String, Number],
      default: ""
    }
  },
  data: function() {
    return {
         currentValue: "",
       valid: false
    }
  },
  watch: {
    value: {
        handler(value) {
                const string = value.trim()
        if (string=="") {
            this.valid = false
        } else {
            this.valid = true
        }
        
        this.currentValue = value
      },
      immediate: true
    }
  },
  methods: {
    handleInput() {
        this.$emit("input", this.currentValue);
    }
  }
})

new Vue({
  el: "#app",
  data: {
        modelo: ""
  },
})
.valid {
  border-left: 2px solid #9cff2b !important;
}

.req{
    border-left: 2px solid red;
}

.form-control:focus {
  outline: 0
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <req-input v-model="modelo"></req-input>
  modelo: {{ modelo }}
  
  <script type="text/x-template" id="req-input-template">
    <input 
      type="text" 
      v-model="currentValue"
      @input="handleInput"
      :class="['form-control req', { 'valid': valid }]" />
  </script>
</div>

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

Issue with create-react-app and express server not displaying correctly in Internet Explorer

My application functions perfectly with Chrome and Safari. It utilizes React for the front-end and Express for the back-end. However, when I try to open it in Internet Explorer, all I see is a blank white page. Additionally, I encounter this error message: ...

Unable to load JSON model texture

I successfully transformed an obj file into a json model using a Python tool, and now I am attempting to load it into my project. Below is the code snippet: var camera, scene, renderer; var mesh, aircraft; function addModelToScene( geometry, materials ) ...

Pass data to three.js using an input form

I'm trying to figure out how to pass the value of an input form to a three.js workspace. Here's my code where I want to use a slider to change the radius of a sphere, without relying on the built-in controls of three.js since I'm new to HTML ...

The word "await" is a special reserved keyword used to call functions within an async

Currently utilizing async-await: Whenever the function run invokes findLateastVersion, even though run function is marked as async, an error message pops up stating await is a reserved word. The findLateastVersion method returns a promise and based on va ...

Controlling LED lights using Johnny-Five and Arduino in NW.js

I have a setup with my board that includes two buttons (each with pull-up resistors) and two LEDs. My goal is to make each button activate its corresponding LED while deactivating the other one. Here's the code I'm using: var five = require(&ap ...

Mastering the art of knowing when to implement asynchronous and synchronous programming techniques is essential for

As I explore asynchronous programming in JavaScript, I am faced with the challenge of integrating two email providers: Sendgrid and Mailgun. My goal is to send an email using one provider, and if any errors occur during the process, automatically resend th ...

Using python to scrape images from a website with AJAX using selenium and beautifulsoup

After spending a considerable amount of time delving into html, javascript, network traffic, and expanding my knowledge on javascript, blobs, and base64 encoding/decoding of images, I am still struggling to extract images from videos on a particular websit ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

Why does one of the two similar javascript functions work while the other one fails to execute?

As a new Javascript learner, I am struggling to make some basic code work. I managed to successfully test a snippet that changes text color from blue to red to ensure that Javascript is functioning on the page. However, my second code attempt aims to togg ...

Converting JSON into HTML has me completely baffled

Despite my best efforts, I have managed to navigate my way through the code thus far, but I am puzzled as to why the JSON data is not being sent to the HTML via JavaScript. I can manually input the necessary parts in the developer console after onLoad an ...

Color schemes for items in the Windows store app

I'm having trouble changing the background color of an item in my split application. I've tried using CSS, but nothing seems to work. Here is the template for the item (default style): <div class="itemtemplate" data-win-control="WinJS.Bindin ...

What is the location where Three.js establishes the default shaders for materials?

I've been attempting to locate the exact location where the fragment and vertex shaders are being assigned after creating a Three.js material, but haven't had much success. Using the ParticleSystemMaterial, I have material = new THREE.ParticleSy ...

Calculate the sum of the elements within an array that possess a distinct attribute

I need to calculate the sum of certain elements in an array. For example, let's consider this array: var sampleArray = [ {"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, ...

Transferring data from AJAX to PHP

I am currently developing a project in PHP. I have created an associative array that functions as a dictionary. Additionally, I have a string containing text with placeholders for keys from the array. My goal is to generate a new String where these key wor ...

Can you explain the concept of peer dependencies and plugins to me?

After reading numerous articles and posts on the topic of peer dependencies, I still find myself struggling to fully understand the concept. For instance, if coffee 1.0 has a dependency on milk 1.0, then logically coffee 1.0 would be included in my packa ...

The Vetur package in VScode is experiencing compatibility issues with user snippets functionality

Hey there! I'm currently utilizing VScode with the Vetur extension for Vuejs syntax highlighting and auto complete support. I've been attempting to make some user snippets function with Vetur by adding them to the vue.json file, but so far, it&ap ...

blurring out of an input field and a division element

I am currently working on creating a dropdown suggestion box that hides when the input field and dropdown box are no longer in focus. My HTML code: <input type="text" id="user_address"> <div id="user_address_sg">SUGGESTION</div> <di ...

JavaScript detecting improper XHTML syntax

Is there an effective method to detect malformed XHTML within a string using JavaScript? Given that my page allows user-generated XHTML (from trusted users) to be inserted into the DOM, I aim to identify unclosed or overly closed tags. If found, I intend ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...

How come the Array object transforms into an empty state when an input file is passed as an array element in an ajax request without

When attempting to upload a file without assigning it to an array, the process works fine. However, when trying to assign the file object as an element of an array, $_FILES becomes empty. HTML <input type='file' name='image' class= ...