[英]vue.js making a data property = to the return value of a method
所以我試圖分配 this.clean = this.cleaner。
結果道具是我要過濾的 20 個對象的數組。 我想要一個只有一個有效的 poster_path 值的對象數組,並刪除那些不符合該要求的對象。 因此.filter()。
props: ['results'],
data() {
return {
clean: []
}
},
mounted() {
this.clean = this.cleaner
},
methods: {
cleaner() {
return this.results.filter(o => o.poster_path !== null)
}
}
問題是使用我的 vue devtool Vue 似乎沒有保存 this.cleaner 值。 我得到{"_custom":{"type":"function","display":"<span>ƒ</span> bound cleaner()"}}
boundcleaner {"_custom":{"type":"function","display":"<span>ƒ</span> bound cleaner()"}}
作為 this.clean 的值。
如果我嘗試使用計算值,我會不斷收到“(評估期間的錯誤)”作為 this.clean 的值。
如果我嘗試this.clean = this.cleaner()
它只會保存一個空數組。
試試這個片段。 我認為您的代碼可以簡化為:
const mockData = [ { name: 'abc', poster_path: 1 }, { name: 'def', poster_path: null } ] Vue.component('foo', { props: ['results'], template: '<ul><li v-for="c in clean" :key="index">{{c.name}}</li></ul>', computed: { clean: function() { return this.results ?this.results.filter(o => o.poster_path !== null) : []; } } }) var app = new Vue({ el: '#app', data() { return { results: mockData } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> Foo component: <foo :results="results"/> </div>
只需像這樣分配函數的功能
props: ['results'],
data() {
return {
clean: []
}
},
mounted() {
this.clean = this.results.filter(o => o.poster_path !== null)
}
props: ['results'],
data() {
return {
clean: this.results.filter(o => o.poster_path !== null)
}
},
請嘗試一下。 你可以直接將 props 導入到組件數據中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.