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

unable to get highcharts to redraw and reflow properly

I am currently working on creating a dynamic page that can display between 1-4 graphs. These graphs need to be able to resize when added or removed from the page. However, I have encountered a major issue with resizing the graphs after resizing the contain ...

Utilize the power of XMLHttpRequest to fetch and load numerous audio files, seamlessly integrating them for playback through the Web Audio

I am looking to create a web application that loads three different audio files, each one second long, in a specific order, and then merges them into a single Audio Buffer consecutively. To illustrate my goal, here is a sample code snippet: var AudioCo ...

Initial button click fails to trigger onclick event

After researching and reading various articles on the issue, I have tried several solutions but nothing seems to work. The problem occurs when the button is clicked for the first time - nothing happens. It is only after clicking the button a second time th ...

Can someone explain the purpose of this code snippet: `const { foo = "bar" } = "baz"`?

I came across this code not too long ago and had trouble finding the answer online, so I'm turning to you for help. The specific code snippet is from a webpack configuration file: const { NODE_ENV = 'production', } = process.env; Appreci ...

Having trouble initiating an AJAX call in Django and returning values to my form

Seeking assistance to run an AJAX call for a quick calculation in my django view and display the result within a span tag on my HTML page. New to Javascript, struggling with triggering my AJAX call. Below is my HTML and JS code: <input type="text" nam ...

Enhancing the background of a website with the power of CSS

I am looking to create a customized table without the balls/pots in it. The number of rows on the y-axis will vary depending on the number of names I have, and can be more or less. The values on the x-axis are determined by a parameter included in the URL ...

"Extracting information from the axios header and passing it to a Vue component: A step-by-step

I am working with an axios apiClient and trying to retrieve the email stored in localStorage to use in the header of my component. I attempted to access the email by using response.headers['email'] and storing it in a variable called email, but ...

Access the id of an object in an array using Vue.js

Is there a way to showcase value data depending on the index array? I have created a modal for editing data, with a JSON structure like this: [ { "ID": 3, "idusers": 3, "skills": "Go", ...

Error: The prop type validation failed because a `value` prop was provided to a form field in React-Bootstrap-Typehead component

I am currently using the bootstrap-typehead package from https://github.com/ericgio/react-bootstrap-typeahead and struggling to understand why it's causing issues. Could someone help me identify what's wrong with this code that's triggering ...

How can I omit extra fields when using express-validator?

Currently, I am integrating express-validator into my express application and facing an issue with preventing extra fields from being included in POST requests. The main reason for this restriction is that I pass the value of req.body to my ORM for databas ...

Window backdrop being filled

I am attempting to set a background image that fills the entire window regardless of its size. I have implemented html, css and script as shown below: // Function adaptImage() // Parameters: targetimg function adaptImage(targetimg) { var wheight = $ ...

Troubleshooting Vue.js: Facing Issues with Unmuting v-if Video Embed - Getting Error Message 'Unmuting Failed...no user interaction with the document detected'

I integrated a 'screensaver' feature in my Vue app that activates after a period of user inactivity. When triggered, a muted Vimeo iframe with autoplay is faded in using v-if, and it works smoothly. However, the issue arises when I attempt to un ...

Use npm to include a new dependency from the current dependency structure

I am currently working on a Vue application that utilizes both vuetable-2 and vue-axios. In my app.js file, I have the following imports: import Vue from 'vue' import VueMaterial from 'vue-material' import axios from 'axios' ...

What is the process for updating input data after loading data from onSSR?

I've been encountering an issue with loading my shipping data from the server (onSSR) and updating it to my input form. Despite placing my code within onSSR as follows, the update does not occur: onSSR(async () => { await load(); await ...

What is the best way to resize images while also maintaining their ability to transition on hover?

Having an interesting dilemma here.. I'm trying to utilize this CSS code: .custom-forums { height: auto; width: 100%; border-image-source:transparent url("../images/forums.png") center top no-repeat; } in combination with: .custom-forum ...

Ways to retrieve dictionary keys as an array in Angular

Here is an example of an Angular dictionary: { ARRAY1: [{...}, {...}, {...}] ARRAY2: [{...}, {...}, {...}] ARRAY3: [{...}, {...}] ARRAY4: [{...}] } I want to show all the keys of arrays from this dictionary on an HTML page. I attempted to do ...

Once the promise program enters the if-condition, even though the condition itself is actually false

There seems to be an issue with retrieving the location code using the AccuWeather API before getting the weather data for a city. Despite the location array being empty, the program still proceeds to a branch that expects a non-empty array. router.get(& ...

Prevent the use of harmful language by implementing jQuery or JavaScript

Is there a way for me to filter certain words (such as "sex") using regex, even when people use variations like "b a d", "b.a.d", or "b/a/d"? How can I prevent these kinds of words from getting through? I'm trying to filter more than just one word - ...

ReactAppI am facing an issue where the browser fails to refresh the page upon saving changes in my JavaScript file using the VS code editor

Can anyone remind me of the tool we can install to refresh the browser page automatically whenever we save changes in our editor? ...

Enhance Your jQuery Experience with Advanced Option Customization

I am currently developing a plugin that deals with settings variables that can be quite deep, sometimes reaching 3-4 levels. Following the common jQuery Plugin pattern, I have implemented a simple method for users to update settings on the go using the not ...