【发布时间】:2020-06-22 23:50:56
【问题描述】:
我正在尝试在我正在制作的待办事项测试站点的模板内的函数内传递道具。基本上我想要一个列表项,其中包含待办事项项,旁边有一个按钮,可以删除相同的项。
Vue.component("todo-item", {
props: ["todotext"],
template: "<li>{{todotext.text}} <button v-on:click='removeThisItem({{todotext}})'>X</button></li>",
})
var next_id = 3
var app = new Vue ({
el: "#app",
data: {
message: "",
todos: [
{id: 0, text: "Do assignment"},
]
},
methods: {
addTodoItem: function () {
this.todos.push({id: next_id, text: this.message})
next_id += 1
},
removeThisItem: function removeThisItem (item) {
this.todos.splice(this.todos.indexOf(item))
}
}
})
和 HTML
<div id="app">
<input type="text" name="" v-model="message">
<button type="button" name="button" v-on:click="addTodoItem">Add Todo Item</button>
<ul>
<todo-item
v-for="todo in todos"
v-bind:todotext="todo"
v-bind:key="todo.id">
</todo-item>
</ul>
</div>
但是我得到了错误
invalid expression: Unexpected token '{' in removeThisItem({{todotext}})
有没有办法在这个模板内的这个函数中将 prop 作为参数传递,以便能够删除这个列表项?
编辑:这里是 JSFiddle:https://jsfiddle.net/f6sn52w8/
谢谢!
【问题讨论】:
-
去掉花括号,只用
<button v-on:click='removeThisItem(todotext)'>X</button>就可以了适当地。请记住,当您使用on:click时,=符号之后的部分将作为 javascript 处理,因此 Javascript 中的 {{todotext}} 没有意义,这就是为什么您必须传递要使用的变量的原因. -
@AndresForonda 嘿,谢谢,我试过了,但它似乎不起作用。它只是说 removeThisItem 不是一个函数。我做了一个 JSFiddle jsfiddle.net/f6sn52w8
标签: vue.js