[英]In Vue.js, how can I emit multiple value from child to parent while parent's v-on pass another parameter?
This is a code example.这是一个代码示例。
Vue.component('button-counter', {
template: '<button v-on:click="emit_event">button</button>',
methods: {
emit_event: function () {
this.$emit('change', 'v1', 'v2', 'v3') // Here I emit multiple value
}
},
})
new Vue({
el: '#parent',
data: {
args: ""
},
methods: {
change: function (...args) {
this.args = args
console.log(args)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.common.js"></script>
<div id="parent">
{{ args }} <br />
<button-counter v-on:change="change(1234, $event)"></button-counter>
</div>
From the parent component, I want to get parameter pass by change() (in this example, 1234), but also every value emitted by child component.从父组件中,我想通过 change() 获取参数传递(在本例中为 1234),而且还希望获得子组件发出的每个值。 I try to use $event to catch the values child emit, however $event is only set up to the first value child emit (int this example, 'v1')
我尝试使用 $event 来捕获 child 发出的值,但是 $event 仅设置为 child 发出的第一个值(int 这个例子,'v1')
Is there any way to do that?有没有办法做到这一点? I know I can emit an array to catch multiple value.
我知道我可以发出一个数组来捕获多个值。 But some library just emit multiple value.
但是有些库只是发出多个值。
This is the codepen for above example.这是上面例子的代码笔。 https://codepen.io/anon/pen/MmLEqX?editors=1011
https://codepen.io/anon/pen/MmLEqX?editors=1011
Define a handler that accepts the multiple parameters from the event and passes them along to the change method in addition to your static parameter.定义一个处理程序,它接受来自事件的多个参数,并将它们传递给除静态参数之外的 change 方法。
<button-counter v-on:change="(...args)=>this.change(1234,...args)"></button-counter>
Alternatively或者
<button-counter v-on:change="(...args)=>this.change([1234,...args])"></button-counter>
And change your method to并将您的方法更改为
change: function (args) {
this.args = args
console.log(args)
}
You can use destructuring syntax您可以使用解构语法
this.$emit('change', { x:'v1', y:'v2', z: 'v3' })
And you can access these values like so你可以像这样访问这些值
<button-counter @change="change"></button-counter>
methods: { change({x, y, z}) { .... } }
我会这样做:
<button-counter v-on:change="change(1, ...arguments)">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.