我的狀態包含以下屬性:
sentences: [
{
text: "Go away and hide behind that door where we found you just now.",
grade: 606
},
{
text: "Please don't let anyone spoil these nice fresh flowers.",
grade: 609
},
]
現在我試圖迭代這些句子,在每個句子上創建一個名為 words 的新屬性,這將是一個單詞陣列。當我 console.log(this.sentences) 時,我看到了新屬性,但是當我嘗試在 DOM 中呈現該屬性時,它沒有顯示新屬性。
mounted(){
this.sentences.map((sentence) => {
const arrayOfWords = sentence.text.split(' ');
sentence.words = arrayOfWords
})
console.log(this.sentences)
}
uj5u.com熱心網友回復:
Array#map 回傳:
一個新陣列,每個元素都是回呼函式的結果。
此外,您需要添加在每次迭代中計算的值:
為 arr 的每個元素呼叫的函式。每次執行 callbackFn 時,回傳值都會添加到 newArray。
因此,要獲得更新的版本,您需要將其分配給this.sentences:
new Vue({
el: "#app",
data: () => ({
sentences: [
{ text: "Go away and hide behind that door where we found you just now.", grade: 606 },
{ text: "Please don't let anyone spoil these nice fresh flowers.", grade: 609 }
]
}),
mounted(){
this.sentences = this.sentences.map(sentence => {
const arrayOfWords = sentence.text.split(' ');
sentence.words = arrayOfWords
return sentence;
})
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(sentence, i) in sentences" :key="i">{{sentence.words}}</div>
</div>
更好的方法是創建一個computed property回傳包含單詞的句子串列:
new Vue({
el: "#app",
data: () => ({
sentences: [
{ text: "Go away and hide behind that door where we found you just now.", grade: 606 },
{ text: "Please don't let anyone spoil these nice fresh flowers.", grade: 609 }
]
}),
computed: {
sentencesWithWords: function() {
return this.sentences.map(sentence => {
const arrayOfWords = sentence.text.split(' ');
sentence.words = arrayOfWords
return sentence;
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(sentence, i) in sentencesWithWords" :key="i">{{sentence.words}}</div>
</div>
uj5u.com熱心網友回復:
Array.map()不會改變原始陣列。它回傳一個新陣列。您需要將其存盤在this.sentences. 或用于forEach()改變原始陣列:
mounted(){
this.sentences.forEach(sentence => {
const arrayOfWords = sentence.text.split(' ');
sentence.words = arrayOfWords
})
console.log(this.sentences)
}
或者
mounted(){
this.sentences = this.sentences.map(sentence => {
sentence.words = sentence.text.split(' ');
return sentence
})
console.log(this.sentences)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/333209.html
上一篇:從磁盤洗掉Ubuntu出現的問題
下一篇:vue-資料參考另一個資料
