Нет доступа к this компонента в computed свойстве
Вот такой кодик:
components: {Help},
props: ['nav_elements'],
name: "Navigations",
computed: {
politics_show: () => {
this.politics_show_ = !this.politics_show_;
return this.politics_show_;
},
},
data: () => ({
politics_show_: false
}),
Использую так:
<v-list-item>
<v-list-item-icon>
<v-container
v-on:click="politics_show"
style="padding: 0; margin: 0"
>
<v-icon> mdi-alert-circle </v-icon>
</v-container>
</v-list-item-icon>
<v-list-item-content/>
</v-list-item>
Получаю такое:
[Vue warn]: Error in render: "TypeError: Cannot read property 'politics_show_' of undefined"
found in
---> <Navigations> at src/components/Navigations.vue
<VApp>
<Courses> at src/views/Courses.vue
<VContent>
<App> at src/App.vue
<Root>
Видимо, прикол в том, что computed вычисляется первый раз до того, как посчитается data. Обойти не получилось. Как поступают обычно?
Ответы (1 шт):
Нет, вы не правы, data вычисляется вперед computed.
Ошибка говорит, что свойство politics_show_ не может быть прочитано у undefined.
Ругается на this.politics_show_. this является undefined.
Это потому что стрелочные функции не имеют this, this берется из контекста выше (https://learn.javascript.ru/arrow-functions#u-strelochnyh-funktsiy-net-this)
Не используйте стрелочные функции в computed, если вам нужен доступ к экземпляру Vue
computed: {
politics_show () {
this.politics_show_ = !this.politics_show_;
return this.politics_show_;
},
},
Не используйте стрелочные функции в свойствах экземпляра и в коллбэках, например
created: () => console.log(this.a)или
vm.$watch('a', newVal => this.myMethod()).Так как стрелочные функции не имеют собственного
this, тоthisв коде будет обрабатываться как любая другая переменная и её поиск будет производиться в областях видимости выше до тех пор пока не будет найдена, часто приводя к таким ошибкам, как
Uncaught TypeError: Cannot read property of undefinedили
Uncaught TypeError: this.myMethod is not a function.
С сайта ru.vuejs.org