【发布时间】:2018-09-04 07:30:21
【问题描述】:
我是 Vue.js 的新手。我正在尝试从我的孙子组件(卡片)向子组件(手)和从手到父组件(主)发出一个事件:
card(发出播放事件) => 手(听播放事件并发出 card-play event) => main(听card-play event)
播放事件应该触发纸牌播放事件
在卡片组件中,我在点击卡片时发出“播放”事件,然后在我的手组件中我正在监听“播放”事件,以便我可以向父级(主)发出“卡片播放”事件.但是既没有发出事件,也没有元素工作(按钮元素被禁用)。
如果我直接在我的主要组件中调用卡片组件,一切正常,但是当我尝试在它们之间放置另一个组件(手)时,没有任何工作。
这是我的代码:
new Vue({
name: 'game',
el: '#app',
data: state,
template: `
<div id="#app">
<card :def="testCard" @click.native="handlePlay2" />
<transition name='hand'>
<hand :cards="testHand" v-if="!activeOverlay" @card-play="testPlayCard" />
</transition>
</div>
`,
methods: {
testPlayCard(card) {
console.log('You played a card!');
},
handlePlay2() {
console.log('You played a card!');
}
},
created() {
this.testHand = this.createTestHand();
},
computed: {
testCard () {
return cards.archers
},
}
});
这里是组件:
/* ----- CARD COMPONENT ----- */
Vue.component('card', {
props: ['def'],
template: `
<div class="card" :class="'type-' + def.type" v-on:click.native="firePlayEvent">
<div class="title">{{ def.title }}</div>
<img class="separator" src="svg/card-separator.svg" />
<div class="description">
<div v-html="def.description"></div>
</div>
<div class="note" v-if="def.note">
<div v-html="def.note"></div>
</div>
<button>bos</button>
</div>
`,
methods: {
firePlayEvent: function() {
this.$emit('play');
console.log("play event is emitted???")
}
},
});
/* ----- HAND COMPONENT ----- */
Vue.component('hand', {
props: ['cards'],
template: `
<div class="hand">
<div class="wrapper">
<!-- Cards -->
<card v-for="card in cards" :key="card.uid" :def="card.def" @play=handlePlay(card) />
</div>
</div>
`,
methods: {
handlePlay(card) {
this.$emit('card-play', card);
console.log("custom event card-play>>");
}
},
});
我将所有数据保存在 state.js 中:
// Some usefull variables
var maxHealth = 10
var maxFood = 10
var handSize = 5
var cardUid = 0
var currentPlayingCard = null
// The consolidated state of our app
var state = {
// World
worldRatio: getWorldRatio(),
// TODO Other things
turn: 1,
//
players: [
{ name : 'Humoyun' },
{ name : 'Jamshid' },
],
//
currentPlayerIndex: Math.round(Math.random()),
//
testHand: [],
//
activeOverlay: null,
//
}
【问题讨论】:
-
你能提供一个jsfiddle链接吗?
-
我会把它上传到github然后我会放一个链接在这里
标签: javascript vue.js