如何使用$ emit函数正确地将参数从子节点传递给父节点? 在这里我做了什么
HTML
template'
<span class="pull-right forward"
v-on:click="centraNellaMappa(single.x,single.y,single.selected)"></span>',
methods:{
centraNellaMappa : function(x,y,selected){
this.$emit('centramappa',[x],[y],[selected]);
}
}
COMPONENT
mappaCenter : function(x,y,selected){
alert(x);
}
家长功能
{{1}}
&#39; x&#39;参数似乎无法识别
答案 0 :(得分:5)
实际上你几乎就在那里,唯一的问题是你用于内联自定义事件处理程序的写作风格。
v-on:centramappa="mappaCenter(x,y,selected)"
vue将在vue实例(this.x
...)中查找x,y和所选变量。由于您未在实例中定义它们,因此会抛出错误
所以你有3个解决方案来解决这个问题。
v-on:centramappa="mappaCenter"
Vue.component('lista-servizi-gialla', {
template: `
<span class="pull-right forward"
v-on:click="centraNellaMappa(3, 5, true)">
test
</span>
`,
methods:{
centraNellaMappa : function(x, y, selected) {
this.$emit('centramappa', [x], [y], [selected]);
}
}
});
new Vue({
el: '#app',
methods: {
mappaCenter: function(x, y, selected){
//alert(x);
console.log(`x: ${x}, y: ${y}, selected: ${selected}`);
}
}
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<lista-servizi-gialla v-on:centramappa="mappaCenter"></lista-servizi-gialla>
</div>
&#13;
$event
的特殊变量,其值将被设置为您在$emit
事件中传递的第一个参数。v-on:centramappa="mappaCenter($event)"
Vue.component('lista-servizi-gialla', {
template: `
<span class="pull-right forward"
v-on:click="centraNellaMappa(3, 5, true)">
test
</span>
`,
methods:{
centraNellaMappa : function(x, y, selected) {
this.$emit('centramappa', {x, y, selected});
}
}
});
new Vue({
el: '#app',
methods: {
mappaCenter: function({ x, y, selected }){
//alert(x);
console.log(`x: ${x}, y: ${y}, selected: ${selected}`);
}
}
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<lista-servizi-gialla v-on:centramappa="mappaCenter($event)"></lista-servizi-gialla>
</div>
&#13;
mappaCenter
方法,则可以使用JavaScript规范中定义的参数变量。v-on:centramappa="mappaCenter(...arguments)"
v-on:centramappa="mappaCenter(arguments[0], arguments[1], arguments[2])"
Vue.component('lista-servizi-gialla', {
template: `
<span class="pull-right forward"
v-on:click="centraNellaMappa(3, 5, true)">
test
</span>
`,
methods:{
centraNellaMappa : function(x, y, selected) {
this.$emit('centramappa', [x], [y], [selected]);
}
}
});
new Vue({
el: '#app',
methods: {
mappaCenter: function(x, y, selected){
//alert(x);
console.log(`x: ${x}, y: ${y}, selected: ${selected}`);
}
}
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
<lista-servizi-gialla v-on:centramappa="mappaCenter(arguments[0], arguments[1], arguments[2])"></lista-servizi-gialla>
</div>
&#13;