繁体   English   中英

程序化组件上的 Vue 反应性道具

[英]Vue reactive props on programmatic component

给定一个组件:

Vue.component('my-comp', {
  props: ['input'],
  watch: { input: function(){...} },
});

以下的程序化方法是什么?

<my-comp :input="map[key]"></my-comp> map[key] change triggers watch

我努力了:

new (Vue.component('my-comp'))({
  propsData: { input:map[key] }, // map[key] change doesn't trigger watch
});

上下文是将零对多组件插入到 Markdown 生成的 HTML 中。 我为每个组件调用.$mount() ,并在重新渲染 markdown 时使用本机 DOM replaceChild()调用移动其节点。 另请参阅用户定义的降价中的 Vue 组件

渲染函数是创建和插入组件的编程方式。 使用newpropsData主要用于单元测试,其中组件不一定有一个 Vue 实例作为父级。

$mount不建立父子关系,它只是将组件独立安装到 DOM。 您将需要设置父子道具管理。

 Vue.component('my-comp', { template: '<div>{{ input }}</div>', props: ['input'] }); new Vue({ el: '#app', data: { thingy: 5, child: null }, created() { this.child = new(Vue.component('my-comp'))({ propsData: { input: this.thingy } }); this.$watch('thingy', (newValue) => this.child.$props.input = newValue); setInterval(() => ++this.thingy, 2000); }, mounted() { this.child.$mount(this.$el); } });
 <script src="//unpkg.com/vue@latest/dist/vue.js"></script> <div id="app"> <div>

如果 prop input 是原始值,我们必须按照 Roy J 的建议使用child.$props.input = x来操作组件,但在这种情况下,我们需要input = map[key] 因此这个解决方案:

Vue.component('my-comp', {
  props: ['map','key'],
  computed: { input: function() { return this.map[this.key] } },
  watch: { input: function(a, b) {...} }, // triggered on map[key] change
});

new (Vue.component('my-comp'))({
  propsData: { map:theMap, key:theKey }, // theMap must be reactive
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM