Vue,同一组件的多个实例以某种奇怪的方式处理事件
Vue, multiple instances of same component handling events in some strange way
我正在尝试使用相同组件的两个实例。
我实现了两个方法,当两个实例之一发出事件时应该调用它们。
两个实例之间的唯一区别是instance1应该调用method1而instance2应该调用method2。
碰巧无论哪个组件发出事件,method1 总是被调用。
我是不是漏掉了什么?
这是我正在做的一个简短例子
自定义组件
<template>
....// Some code that at a certain point calls myMethod
</template>
<script>
export default {
methods: {
myMethod () {
this.$emit('picture-taken')
}
}
}
</script>
我正在使用 CustomComponent 的页面
<template>
<custom-component @picture-taken="func1" />
<custom-component @picture-taken="func2" />
</template>
<script>
export default {
methods: {
func1() {
debugger
//It always ends up here
},
func2() {
debugger
},
}
}
</script>
这种代码适用于您的用例。
parent page
<template>
<div>
<child :id="1" @picture-taken="callSpecificFunction"></child>
<child :id="2" @picture-taken="callSpecificFunction"></child>
</div>
</template>
<script>
export default {
auth: false,
methods: {
callSpecificFunction(id) {
console.log('id emitted', id)
this[`function${id}`]()
},
function1() {
console.log('function1 called')
},
function2() {
console.log('function2 called')
},
},
}
</script>
Child.vue
<template>
<button @click="emitPlease">please do emit for id {{ id }}</button>
</template>
<script>
export default {
props: {
id: {
type: Number,
default: 1,
},
},
methods: {
emitPlease() {
this.$emit('picture-taken', this.id)
},
},
}
</script>
我正在尝试使用相同组件的两个实例。 我实现了两个方法,当两个实例之一发出事件时应该调用它们。 两个实例之间的唯一区别是instance1应该调用method1而instance2应该调用method2。
碰巧无论哪个组件发出事件,method1 总是被调用。
我是不是漏掉了什么?
这是我正在做的一个简短例子
自定义组件
<template>
....// Some code that at a certain point calls myMethod
</template>
<script>
export default {
methods: {
myMethod () {
this.$emit('picture-taken')
}
}
}
</script>
我正在使用 CustomComponent 的页面
<template>
<custom-component @picture-taken="func1" />
<custom-component @picture-taken="func2" />
</template>
<script>
export default {
methods: {
func1() {
debugger
//It always ends up here
},
func2() {
debugger
},
}
}
</script>
这种代码适用于您的用例。
parent page
<template>
<div>
<child :id="1" @picture-taken="callSpecificFunction"></child>
<child :id="2" @picture-taken="callSpecificFunction"></child>
</div>
</template>
<script>
export default {
auth: false,
methods: {
callSpecificFunction(id) {
console.log('id emitted', id)
this[`function${id}`]()
},
function1() {
console.log('function1 called')
},
function2() {
console.log('function2 called')
},
},
}
</script>
Child.vue
<template>
<button @click="emitPlease">please do emit for id {{ id }}</button>
</template>
<script>
export default {
props: {
id: {
type: Number,
default: 1,
},
},
methods: {
emitPlease() {
this.$emit('picture-taken', this.id)
},
},
}
</script>