Abdelaziz Mokhnache
Abdelaziz Mokhnache

Reputation: 4349

How to access a method from vuejs component?

I am building a Tic Tac Too game with vue.js framework. I have declared a vue component called grid-item, when this item is clicked I want it to call the handleClick method.

when I run the code bellow it logs to the console that the handleClick method is not defined.

How to fix the problem and get access to this method from the component ?

// 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>

Upvotes: 2

Views: 2384

Answers (1)

Saurabh
Saurabh

Reputation: 73609

You are getting this error as you have defined handleClick method in component : app but you are using this in the template of grid-item, where it is not defined.

Scope of vue methods is limited to the instance they have been defined.

// 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,
    }
})
* {
  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>

Upvotes: 5

Related Questions