簡體   English   中英

Vue.js 組件在 data 屬性中調用一個方法

[英]Vue.js component call a method inside data property

我想將組件方法分配給數據變量,請參閱下面的示例代碼。 可悲的是它不起作用,正確的方法是什么?

<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")
        }
    }
}

嘗試將 vue 實例 ( this ) 作為參數傳遞給數據函數data: (vm) =>然后使用它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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM