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?