[英]How to show items in list uppercase?
我正在嘗試在 vue 中制作簡單的列表示例(A TODO LIST)。在這里我正在嘗試添加大寫過濾器(換句話說,所有字母都大寫)。但它顯示的是我的錯誤
這是我的代碼https://plnkr.co/edit/THtaYSnGkBp7BlMYcNUl?p=preview
var app = new Vue({
el: '#App',
data: {
message: '',
items: [{
name: "test1"
}, {
name: "test2"
}, {
name: "test3"
}]
},
methods: {
addTodo: function () {
this.items.push({
name:this.message
});
this.message ='';
},
deleteTodo:function (item) {
console.log(item)
var index = this.items.indexOf(item);
this.items.splice(index, 1);
}
},
computed: {
upperCase: function () {
return this.items.map(function (item) {
return this.item.upperCase();
})
}
}
})
錯誤:渲染函數中的錯誤:“TypeError:無法讀取未定義的屬性‘大寫’”
**vue.js:572 TypeError: Cannot read property 'upperCase' of undefined
at script.js:29
at Array.map (<anonymous>)
at Vue$3.upperCase (script.js:28)
at Watcher.get (vue.js:2883)
at Watcher.evaluate (vue.js:2990)
at Proxy.computedGetter (vue.js:3265)
at Proxy.eval (eval at createFunction (vue.js:9818), <anonymous>:2:311)
at Vue$3.Vue._render (vue.js:4123)
at Vue$3.updateComponent (vue.js:2542)
at Watcher.get (vue.js:2883)**
您可以一起跳過 javascript 並使用 CSS 將文本變為大寫。
.uppercase { text-transform: uppercase; }
<p class="uppercase">I am uppercase</p> <p>I am normal case</p>
您在map
中的函數應該引用item
(它的參數)而不是this.item
,它不存在,因為該函數沒有被作為方法調用。
你犯過的錯誤:
upperCase()
不是 javascript 函數。 它應該是toUpperCase()
。this.item
,只需在回調函數中使用item
。item
是一個對象,因此您不能執行toUpperCase()
方法。 你必須做item.name.toUpperCase()
(這就是你想要做的)。 將您的upperCase
函數更改為:
upperCase: function () {
return this.items.map(function (item) {
return item.name.toUpperCase();
})
}
您正在從upperCase
函數返回值,但試圖在index.html
文件中顯示item.name
。 將其更改為僅item
。
<li v-for="item in upperCase" > {{item}} <button @click="deleteTodo(item)">X</button> </li>
更新 plnkr: https ://plnkr.co/edit/17dCvKKDa7EgwHetzzMR?p=preview
對於可能的未來讀者,過濾器是專門為此而設計的,其優點是可重用,而不是為您需要大寫的每個列表提供計算屬性。
Vue.js 允許您定義可用於應用常見文本格式的過濾器。
模板:
<li v-for="item in items" >
{{item.name | capitalize}}
<button @click="deleteTodo(item)">X</button>
</li>
篩選:
filters: {
capitalize: function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.