Using Vue components alongside vanilla JavaScript code

I am currently working on integrating Vue.js into an existing project that does not utilize Vue. Unfortunately, I have been unable to find any resources or documentation on how to create a Vue component with an API that can be accessed by external code outside of the Vue framework. Most available information is directed towards building full applications with Vue from scratch.

var MyV = Vue.extend({
  template: `
    <div>
        <h4>{{ message }}</h4>
        <ul>
            <li v-for="item in items">
                {{item}}
                <button v-on:click="remove(item)">-</button>
            </li>
        </ul>
        <button v-on:click="add">add</button>
    </div>
    `,
  data() {
    return {
      message: 'Hello Vue.js!',
      items: ['foo', 'bar'],
    };
  },
  methods: {
    add() {
      this.items.push(Math.random());
    },
    remove(item) {
      this.items.splice(this.items.indexOf(item), 1);
    }
  }
});

var v = new MyV({
  el: c1
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4335362603716d766d7b">[email protected]</a>/dist/vue.js"></script>

<div id="c1"></div>

One thing I have discovered through experimentation:

When interacting with Vue externally, I can manipulate the v instance and see changes reflected in the view.

// everything works
v.message = "Hi there!";
v.items.push('hello');
v.items.add();

How can I listen for an "onchange" event? There are several ways to approach this, but is there an official method?

Setting properties is simple, but how do I retrieve data from the view once it has been modified?


For example, if I were creating a dropdown menu with Vue, I could populate this "component" by setting a property.

If the view contains a "submit" button, how can I alert external code when the user clicks it?

If the view allows the user to modify its internal state (this.data), how can external code be notified of these changes so it can access the updated content?

Answer №1

Just like how you can invoke v.add() externally in Vue code, it is possible to observe value properties from external sources:

v.$watch('items', (newValue) => { console.log("Items modified!", newValue); });

Furthermore, you have the option to utilize v.$emit and v.$on for transmitting and receiving custom events, as each Vue instance serves as an event communicator.

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

How can you prevent the blur event from triggering in jQuery when the next element to receive focus is of a specific type?

I am currently developing a unique form UI where I am working on creating a custom select box replacement. The custom select control consists of a hidden select input within a div, along with anchor elements inside a span that mimic the options of the sele ...

VueJS: The current date is before today's date when using Date.now

I am currently comparing two dates in order to perform a filtered search. My goal is to only include objects in the filtered results if the date is after today, excluding any objects dated for today. However, when I run my code, it appears that items wit ...

Modifying HTML line codes using Python: A step-by-step guide

If only I could modify this particular line: <button _ngcontent-c19="" class="blue-button-disabled" disabled="">CONTINUE </button> to be like this instead: <button _ngcontent-c19="" class="blue- ...

After making the request, $.getJSON initially comes back as undefined but eventually delivers

I found myself in a sticky situation. I was working on coding a Wikipedia search tool for a personal project, but encountered a small glitch. When a user types a word into the search bar, it gets stored in the data parameter of $.getJSON. The response then ...

The AJAX request encountered an error due to an Unexpected End of JSON Input

My AJAX code is encountering an error message. parsererror (index):75 SyntaxError: Unexpected end of JSON input at parse (<anonymous>) at Nb (jquery.min.js:4) at A (jquery.min.js:4) at XMLHttpRequest.<anonymous> (jquery.min.js: ...

Mocking objects in unit test cases to simulate real-life scenarios and test the

How do I pass a mocked event object and ensure it is validated? onCallFunction() { const eventValue = event; if (!eventValue.relatedTarget || !eventValue.relatedTarget.last.contain('value')) { super.onCallFuncti ...

Navigating to a different directory using Node.js and ExpressJS route mapping

I'm struggling with setting up routing using ui.router. This is the structure of my folders: https://i.stack.imgur.com/Fu0A9.png In the app.js file within the javascripts folder, I have the following code: var app = angular.module('testing&ap ...

Having difficulty handling file data following the import of an Excel file in Laravel 5.8

I have a requirement to send multiple emails at once by importing an Excel file. Currently, I am successfully importing the Excel file and storing the data in a variable as an array. I am utilizing maatwebsite/excel version 3.1 for this task. However, afte ...

Execute a post request upon clicking with NEXT JS, while also firing off a get request

I'm facing an issue where I need to post and get my data when clicking on the same button (similar to writing and displaying comments). However, whenever I click the button, everything seems to be working fine but a request with a 304 status code star ...

Invoking middleware within another middleware

I was recently following along with a web development tutorial on YouTube where the instructor introduced two middlewares called verifyToken and verifyUser. `verifyToken` const verifyToken = (req, res, next) => { const token = req.cookies.access_token ...

Struggling with passing data to the API controller in Laravel when attempting to override sendResetLinkEmail with Vue and Vuex integrated

I'm currently working on implementing the forgot password feature for my web application using Laravel along with Vue and Vuex. I came across a helpful tutorial at . I tried to integrate Vuex into this tutorial, but unfortunately, it didn't work ...

What is the best way to save static information (such as country codes) within a Vue.js application?

After researching the most common best practices for handling this issue, I have found no clear answer. How should static content like country codes or arrays of categories be stored in a vue.js app? Storing it in my .env file as an environment variable se ...

What is the best way to create a universal variable that can be accessed across all routes in an Express/

Exploring the world of nodejs and express, I have turned to the Parse API for my backend database needs. At the moment, I have an ajax post triggered on page load to one of my routers /getuser, which retrieves the current user if they are logged in. I am ...

Filter the specific output in a generator function

I have a code snippet that I need help with. function* iterateRecord() { const db = yield MongoClient.connect(''); const collection = db.collection(''); const query = {} const cursor = collection.find(query); ...

Can the rxjs take operator be utilized to restrict the number of observables yielded by a service?

As someone who is just starting to learn Angular, I am working on a website that needs to display a limited list of 4 cars on the homepage. To achieve this, I have created a service that fetches all the cars from the server. import { Response } from &apos ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Having trouble with AJAX integration when adding two products to the cart? Looking for a solution to resolve this issue?

In the cart view page, I have noticed that when there is only one product in the cart, I am able to increase and decrease the quantity by clicking on the + and - buttons. However, if I add more than one product to the cart, these buttons do not work for an ...

How to extract a one-of-a-kind identification number from the browser using just JavaScript in a basic HTML file?

Is there a way to obtain a distinct identification number from a browser without resorting to techniques such as generating and storing a unique number in cookies or local storage, and without utilizing a server-side language? ...

Angular.js image slider display for viewing photos

Exploring the possibility of incorporating an open source widget to showcase images on a webpage, specifically leveraging angular.js. After conducting a search query on Google for "Angular.js photo carousel" or "angular.js photo viewer," I discovered only ...

Having issues with JavaScript and MySQL data retrieval following XMLHttp update to the database

After running the newNet.php file successfully creates a new entry and assigns it an auto-incremented netID. The next step is to retrieve this newly created ID and use it in the showActivities() function to display the record. Ideally, it should work like ...