Heim > Fragen und Antworten > Hauptteil
P粉7275312372023-09-04 12:48:32
以下对toggle
函数的绑定对我来说没有任何意义:
:toggleLeft="toggle('left')" :toggleRight="toggle('right')
由于该函数不返回任何值,所以这是错误的。
这两个绑定会导致函数无限调用toggle('left')
和toggle('right')
只需在toggle
函数中添加console.log(direction)
以查看发生了什么。
如果您想获得关于正确解决方案的建议,请描述您想要实现的目标。
Vue.component('toggle-buttons',{
props: {
leftSelectedInitially: {
type: Boolean,
default: true,
}
},
data() {
return {
leftSelected: true,
rightSelected: false,
}
},
beforeMount() {
//this.leftSelected = this.leftSelectedInitially;
//this.rightSelected = !this.leftSelectedInitially;
},
methods: {
toggle(override) {
console.log(`override: ${override}`)
this.leftSelected = override == 'left';
this.rightSelected = override == 'right';
}
},
template: `
<div role="list">
<div role="listitem">
<slot name="left" :is-selected="leftSelected" :toggleLeft="toggle('left')" />
</div>
<div role="listitem">
<slot name="right" :is-selected="rightSelected" :toggleRight="toggle('right')" />
</div>
</div>
`
});
new Vue({
el:'#app',
methods: {
toggle(direction) {
console.log(`direction: ${direction}`)
this.$refs.tb.toggle(direction);
}
}
})
#app { line-height: 2; }
[v-cloak] { display: none; }
<div id="app">
<toggle-buttons ref="tb">
<template v-slot:left="{ isSelected }">
<button
class="button"
:class="{ secondary: !isSelected }"
:aria-pressed="isSelected"
:togglable="true"
v-text="'left'"
@click="toggle('left')"
/>
</template>
<template v-slot:right="{ isSelected }">
<button
class="button"
:class="{ secondary: !isSelected }"
:aria-pressed="isSelected"
:togglable="true"
v-text="'right'"
@click="toggle('right')"
/>
</template>
</toggle-buttons>
</div>
<script src="https://unpkg.com/vue@2/dist/vue.min.js"></script>