问题
I'm using a third-party library that uses class instances with getter/setter properties, and I'd like to control those properties using a VueJS component. I'm not supposed to use the instance as component state directly (Evan You says it's "a rabbit hole"), but if I have to write my own go-between code to map component state to class state, what's the point of reactive data binding in the first place?
Example:
// Toggle.js
var Toggle = Vue.component("Toggle", {
template: '<label><input type="checkbox" v-model="visible">Click me!</label>',
props: ["visible"]
});
// Third-party library
var Widget = function() {
this._visible = true;
}
Widget.prototype = {
get visible(){ return this._visible; },
set visible(v){ this._visible = v; }
}
// app.js
var widgets = [new Widget(), new Widget(), new Widget()];
var v = new Vue({
el: "#content",
template: "<div><toggle v-for='(widget,idx) in widgets' :visible='widget.visible' :key='idx'></toggle></div>",
data: {widgets},
components: { Toggle }
});
<script src="https://vuejs.org/js/vue.js"></script>
<div id="content"></div>
The above example is not the right way to do this for two reasons: one, because props is meant to be a one-way binding from the parent down to the child, and two, because the Widget instance is a complex object that cannot be made reactive.
What's a good design pattern for this case? Remember, I don't control the Widget class so any solution must work without changing its definition.
来源:https://stackoverflow.com/questions/44670492/how-should-i-control-the-state-of-a-class-instance-property-with-a-vue-component