In Vue2 this seems to be break:
<template>
<v-list v-model="itemSelected">
<v-list-item v-for="(item, i) in items" :key="i" @click="item.onClick"
>item.label</v-list-item>
</template>
<script>
export default {
name: 'myTestComponent'
data: () => ({
itemSelected,
items: [
{ label: 'Logout', onClick: this.onLogoutClick },
{ label: 'Settings', onClick: this.onSettingsClick },
{ label: 'Profile', onClick: this.onProfileClick },
]
}),
methods: {
onLogoutClick() {
console.log('LogoutClick')
},
onSettingsClick() {
console.log('SettingsClick')
},
onProfileClick() {
console.log('ProfileClick')
},
},
</script>
The error is that onLogoutClick
is a null reference. This seems to indicate to me that the data
property is created before the methods
property.
Is there a way around this? Perhaps to pass the method names as a string and convert that reference to a method name at call time?
CodePudding user response:
You can pass vue instance to data function, and call methods in onClick
property :
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: (vi) => ({
itemSelected: null,
items: [
{ label: 'Logout', onClick: vi.onLogoutClick },
{ label: 'Settings', onClick: vi.onSettingsClick },
{ label: 'Profile', onClick: vi.onProfileClick },
]
}),
methods: {
onLogoutClick() {
console.log('LogoutClick')
},
onSettingsClick() {
console.log('SettingsClick')
},
onProfileClick() {
console.log('ProfileClick')
},
},
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
<v-app>
<v-main>
<v-container>
<v-list v-model="itemSelected">
<v-list-item v-for="(item, i) in items" :key="i" @click="item.onClick"
>{{item.label}}</v-list-item>
</v-list>
</v-container>
</v-main>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>