我正在使用vue.js框架构建Tic Tac Too游戏。我已经声明了一个名为grid-item
的vue组件,当单击此项时,我希望它调用handleClick
方法。
当我运行下面的代码时,它会在控制台上记录handleClick
方法未定义。
如何解决问题并从组件中访问此方法?
// vue components
Vue.component("grid-item", {
template: "#grid-item",
data: function() {
return {
sign: "X",
owner: ""
}
}
})
// vue instance
new Vue({
el: "#app",
data: {
matriceSize: 3,
},
methods: {
handleClick: function() {
alert("checked");
}
}
})

* {
box-sizing: border-box;
}
#game-box {
width: 150px;
display: block;
margin: 0px auto;
padding: 0px;
background: green;
}
.grid-item {
display: inline-block;
width: 33.333%;
height: 50px;
background: yellow;
margin: 0px;
text-align: center;
line-height: 50px;
border: 1px solid
}

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<div id="game-box">
<grid-item v-for="n in 9"></grid-item>
</div>
</div>
<template id="grid-item">
<div class="grid-item" @click="handleClick"></div>
</template>
&#13;
答案 0 :(得分:3)
您收到此错误,因为您已在组件handleClick
中定义了app
方法,但您在grid-item
的模板中使用此方法,但未定义此方法。
vue方法的范围仅限于已定义的实例。
// vue components
Vue.component("grid-item", {
template: "#grid-item",
data: function() {
return {
sign: "X",
owner: ""
}
},
methods: {
handleClick: function() {
alert("checked");
}
}
})
// vue instance
new Vue({
el: "#app",
data: {
matriceSize: 3,
}
})
&#13;
* {
box-sizing: border-box;
}
#game-box {
width: 150px;
display: block;
margin: 0px auto;
padding: 0px;
background: green;
}
.grid-item {
display: inline-block;
width: 33.333%;
height: 50px;
background: yellow;
margin: 0px;
text-align: center;
line-height: 50px;
border: 1px solid
}
&#13;
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<div id="game-box">
<grid-item v-for="n in 9"></grid-item>
</div>
</div>
<template id="grid-item">
<div class="grid-item" @click="handleClick"></div>
</template>
&#13;