简体   繁体   English

在 Vue 中动态添加带有事件的不同组件

[英]Dynamically adding different components with events in Vue

I want to create a list of similar components that will be added automatically.我想创建一个将自动添加的类似组件的列表。

Something like this:像这样的东西: 组件之间的通信

Dynamic component rendering with Vue is easy, but there is a problem in communication between parent and child in these components.用 Vue 动态渲染组件很简单,但是这些组件中父子之间的通信存在问题。 In the child is a button and when a user clicks on it, the counter in the parent should change.在孩子中是一个按钮,当用户点击它时,父母中的计数器应该改变。

Something like this example:像这个例子:

 const Reusable = { template: '<div>{{ name }} {{ bar }}<button @click="doClick">Click</button></div>', props: { name: { type: String } }, methods: { doClick() { console.log("clicked"); this.$emit("clicked"); } }, data () { return { bar: 'Bar' } } } const App = new Vue({ el: '#app', data: { items: [], value: 0, }, methods: { onClick() { //I want to run this method console.log("onClick method"); this.value = this.value + 1; }, addComponent () { const renderComponent = { render (h) { return h(Reusable, { class: ['foo'], props: { name: 'Foo' }, on: { clicked() { console.log("on clicked in Reusable"); this.onClick(); //why this method cannot be called? }, }, /* events: { clicked: this.onClick() } */ }) } } this.items.push(renderComponent) } } });
 #app { padding: 5rem; }
 <link href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.3.0/milligram.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <component v-for="item in items" ref="itemRefs":is="item":key="item.name"></component> <div> {{value}} </div> <button @click="addComponent">Add Component</button> </div>

You can get rid of the $emit altogether and use @click.native="value++" :您可以完全摆脱$emit并使用@click.native="value++"

 const Reusable = { template: '<div>{{ name }} {{ bar }}<button @click="doClick">Click</button></div>', props: { name: { type: String } }, methods: { doClick() { console.log("clicked"); this.bar = 'Baz'; } }, data() { return { bar: 'Bar' } } } const App = new Vue({ el: '#app', data: { items: [], value: 0, }, methods: { addComponent() { const renderComponent = { render(h) { return h(Reusable, { class: ['foo'], props: { name: 'Foo' }, }) } } this.items.push(renderComponent) } } });
 #app { padding: 5rem; }
 <link href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.3.0/milligram.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <component v-for="item in items" ref="itemRefs":is="item":key="item.name" @click.native="value++"></component> <div> {{value}} </div> <button @click="addComponent">Add Component</button> </div>

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

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