[英]Sending data to a non parent component in VueJs
我正在嘗試在VueJs中復制TODO MVC。 (請簽出此codepen: http ://codepen.io/sankalpsingha/pen/gwymJg)我用以下代碼創建了一個名為“ todo-list”的組件:
Vue.component('todo-list',{
template: '#todo-list',
props: ['todo'],
data: function(){
return {
// Let us set up a isEditing Boolean so that we can know if the user
// will edit something and we need to change the state to reflect it.
isEditing: false
}
},
methods: {
enableEditing: function(){
this.isEditing = true;
},
editTodo: function(todo){
// todo.todo = todo.todo.trim();
this.isEditing = false;
},
removeTodo: function(todo){
//this.todos.$remove(todo); // --> This part is not working?
}
}
});
但是,我在應用實例中定義了數據:
var app = new Vue({
el: '#todo-section',
data: {
newTodo: '',
todos: [
{
id: 1,
todo: 'Go to the grocery',
completed: false
},
{
id: 2,
todo: 'See the movie',
completed: true
},
{
id: 3,
todo: 'Jack Reacher : Tom Cruise',
completed: false
}
]
},
methods: {
addTodo: function(){
// This will not allow any empty items to be added.
if(this.newTodo.trim() == ''){
return;
}
this.todos.push({
todo: this.newTodo.trim(),
completed: false
});
this.newTodo = ''
}
}
});
我無法從列表中刪除單個待辦事項。 我的猜測是我必須向應用程序實例發送發射消息,並在那里放置一個偵聽器以從中刪除數據嗎? 如何刪除數據?
當我嘗試通過單擊您的codePen示例中的x
按鈕刪除時,看到錯誤: this.$parent.todos.$remove
不是一個函數。
我還沒有深入研究您的代碼。 但是嘗試使用this.$parent
訪問父組件方法不是一個好主意。 原因:組件可以在任何地方使用,並且假定該組件具有具有特定屬性或方法的$ parent是有風險的。
正如您在問題中所建議的那樣,您需要使用子組件中的$emit
來刪除數據。
前幾天在這里還有另一個類似的問題,為此我創建了一個jsFiddle: https ://jsfiddle.net/mani04/4kyzkgLu/
子組件具有一些代碼,例如:
<button @click="$emit('delete-row')">Delete</button>
這會將事件發送到父組件。 父組件可以使用v-on
訂閱該事件v-on
如該jsFiddle示例所示。
這是另一個可供參考的問題: 刪除Vue子組件
最好在父母中使用您的方法(DeleteTodo,EditTodo ...)。
var app = new Vue({ el: '#app', data: { newTodo: '', todos: [{ id: 1, title: 'Go to the grocery', completed: false }, { id: 2, title: 'See the movie', completed: true }, { id: 3, title: 'Jack Reacher : Tom Cruise', completed: false }] }, methods: { addTodo: function() { this.todos.push({ todo: this.newTodo.trim(), completed: false }); this.newTodo = '' }, deleteTodo: function(todo) { this.todos = this.todos.filter(function(i) { return i !== todo }) } } });
<div id="app"> <ul> <li v-for="todo in todos">{{ todo.title }} <button @click.prevent="deleteTodo(todo)"> Delete </button> </li> </ul> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.