I'm trying to fit Vue.js inside an existing project that doesn't use Vue. But I could not find any resource or documentation on how I can write a Vue component that have an API that can be used by code outside of the Vue world. Everything is focused on apps built with Vue from top to bottom.
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/[email protected]/dist/vue.js"></script>
<div id="c1"></div>
What I already figured out just by playing around:
From outside of Vue, I can just mutate the v instance and the view changes according.
// everything works
v.message = "Hi there!";
v.items.push('hello');
v.items.add();
How I'm I supposed to listen to a "onchange" event? I can se a few ways of implementing this, but there's an "official" way?
Setting stuff is pretty straightforward, I can just set any property, or initialize it while instantiating, but how do I can get data back from this view?
Let's say I'm building a dropdown menu with Vue, I can populate this "component" just by setting a property.
If there's like a "submit" button inside this view, how I can notify the code outside of the view the user clicked on it?
If the view provides UI for the user modify its internal state (this.data) how code outside can be notified that the data has been modified, and it can then get the content of it again?