【问题标题】:Passing Functions as props in vue js在 vue js 中将函数作为道具传递
【发布时间】:2021-02-24 13:51:21
【问题描述】:

我正在尝试将 editTodo 作为 props 函数从父 app.vue 传递给子组件... TodoItem.vue 组件有一个 Items 列表和 Time 返回给主用户输入的 newTodo 和 dateTime 字段。实际上,我是 Vue js 的新手,对 pass props b/w 组件通信有一点了解。

      <template>
  <div id="app" class="container">
    <TodoInput :addTodo="addTodo"
    :updateTodo="updateTodo" 
    
    />

    <todo-item v-for="(todo, index) in todos" 
    :key=todo.id 
    :todo=todo 
    :index =index 
    :removeTodo="removeTodo"
    :editTodo="editTodo" /> 
    
  </div>

  
 
</template>



<script>
import TodoInput from "./components/TodoInput.vue";
import TodoItem from "./components/TodoItem.vue";
 
export default {
  name: "App",
  components: {
    TodoInput,
    TodoItem,
  
  },
  data() {
    return {
     
      editing:false,
      editItems:{},
      
      
      todos: [
        // {
        //   id: 1,
        //   title: "",
        //   date: new Date(),
        //   editing: false,
        //   completed: false,
        // },
        // {
        //   id: 1,
        //   title: "",
        //   date: new Date(),
        //   editing: false,
        //   completed: false,
        // },
      ],
    };
  },
 

  methods: {
     editTodo(index, newTodo, dateTime){
     , ' dateTime ', dateTime)
    //  this.editItems = {
    //    id,
    //    title,
    //    time,
    //  }
      this.todo = newTodo
      this.todo = dateTime
      this.selectedIndex = index
      this.editing = true
    },

TodoItem.vue 组件中有一个 Items 列表和 Time 返回到 newTodo 和 dateTime 字段的主要用户输入。***enter code here

  • `**

    --> {{todo.title}} {{todo.time}}
    </div>
          <div class="remove-item" @click="removeTodo(index)">
              &times; 
          </div>
           <div class="edit-item"  @click="eiditTodo(index)"
           >
              <i class="fas fa-edit" id="edit"></i>
           </div>
    

导出默认{ 名称:'待办事项', 道具:{ 去做:{ 类型:对象, 要求:真, }, 删除待办事项:{ 类型:功能, 要求:真, }, 指数:{ 类型:数字, 要求:真, },

},
data(){
    return{
        'id': this.todo.id,
        'title': this.todo.newTodo,
        'time': this.todo.dateTime,
      }

methods: 
   
    getEdit(){
     
        this.$emit('editTodo', this.selectedIndex)
    }

**`

【问题讨论】:

标签: vuejs2 vue-component vuex vue-router vue-props


【解决方案1】:

与其将函数作为 props 传递给子组件以运行它,不如从子组件发出事件并在父组件中执行函数。

从子组件发出事件

@click="$emit('edit-todo')"

然后在父组件中

<div @edit-todo="editTodo">
</div>

或者,您可以在TodoItem 组件中定义editTodo 函数并直接调用它。

【讨论】:

    猜你喜欢
    • 2021-04-25
    • 2022-01-25
    • 2018-05-29
    • 2018-11-05
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 2019-11-05
    • 2022-08-12
    相关资源
    最近更新 更多