首页 > 解决方案 > ( Vue.js ) 为什么带有 $emit 的按钮不起作用?

问题描述

问题是,在这种情况下,当我按下按钮 ( <button @click="$emit('remove-todo',task.id)">) 方法时 removeTodo不起作用并且不会在控制台中输出“d”。一般来说,我正在尝试实现可以​​从列表中删除我的待办事项的按钮。我是 Vue 的新手,也许这就是我犯这个愚蠢错误的原因。

控制台中没有错误消息

代码 (Home.vue)

<template>
   <div>
       <h1>Todo List</h1>
       <table v-if="tasks.length">
           <thead>
               <th>#</th>
               <th>Title</th>
               <th>Description</th>
           </thead>
           <tbody>
               <tr 
               v-for="(task, idx) of tasks"
               :key="task.id"
               >
               <td>{{ idx + 1 }}</td>
               <td>{{ task.title }}</td>
               <td>{{ task.description }}</td>
               <td class="close">
                   <button @click="$emit('remove-todo',task.id)" <!-- This button doesn't work -->
                            v-on:remove-todo="removeTodo"
                   ><i class="fas fa-times"></i></button>
               </td>
               </tr>
           </tbody>
       </table>
       <p v-else>No tasks for today.Create a new one</p>
   </div>
</template>

<script>
export default {
    computed:{
        tasks(){
            return this.$store.getters.tasks
        }
    },
    methods:{
        removeTodo(){
            console.log("d")
        }
    }
}
</script>

<style scoped>
h1{
    text-align: center;
}
table{
    display: table;
    border-collapse: collapse;
    background-color: rgba(1, 120, 26, 0.3);
    position: relative; 
    left: 50%;
    transform: translateX(-50%);
    border-radius: 10px; 
       
}
table thead{
    font-size: 25px;

}

table th{
    border-right: 1px solid black;
}
table th:last-child{
    border-right: none;
}
table td{
    width:15rem;
    text-align: center;
    padding: 10px;
    color: white;
    border-top:2px solid black;
    border-right: 1px solid black;
}
table td:last-child{
    border-right: none;
}

.close{
    width: 1rem;
    padding: 0;
    margin: 0;
}
.close button{
    width: 40px;
    height: 40px;
    cursor: pointer;
    background-color: #FF5050;
    border: none;
    outline: none;
    color: #353535;
}
</style>

应用程序.vue

<template>
  <div id="app">
    <Navbar />
  <router-view />
  </div>
</template>

<script>
import Navbar from '@/components/Navbar'
export default {
  name: 'App',
  components: {
    Navbar
  }
}
</script>

<style>

#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
body{
  background-color:#444444;
}
</style>

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'


Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')

如果您能帮我解决这个问题,我将不胜感激

标签: vue.js

解决方案


你可以这样做:

<button @click="removeTodo(task.id)"><i class="fas fa-times"></i></button>

$emit() 将在父组件中发出 removeTodo 如果你有的话。


推荐阅读