2

I'd like to assign component methods to data variables, see the example code below. Sadly it does not work, what is the correct way?

<li v-for="item in items" @click="item.action">
    {{ item.title }}
</li>
export default {
    data: () => ({
        items: [
            { title: "One", action: this.funcOne },
            { title: "Two", action: this.funcTwo },
        ]
    }),
    methods: {
        funcOne() {
            alert("Hi")
        },
        funcTwo() {
            alert("Hello")
        }
    }
}

1 Answer 1

3

Try to pass the vue instance (this) as parameter to the data function data: (vm) => then use it action: vm.funcOne

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
      data: (vm) => ({ // vm the component instance this
        items: [
            { title: "One", action: vm.funcOne},
            { title: "Two", action: vm.funcTwo },
        ]
    }),
    methods: {
        funcOne() {
            alert("Hi")
        },
        funcTwo() {
            alert("Hello")
        }
    }
  })
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">
<li v-for="item in items" @click="item.action">
    {{ item.title }}
</li>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.