美文网首页
【Vue.js】 todolist删除功能实现(十)

【Vue.js】 todolist删除功能实现(十)

作者: kingloongMagic | 来源:发表于2018-09-02 21:17 被阅读0次

子组件与父组件项目通信

思想:面向数据编程,子组件向父组件发送消息与Pyqt类似;
每个方法归属问题:绑定事件定义在哪个组件里面,方法就属于哪个组件

A、子组件向父组件发送消息

第一个参数为消息名称,与Pyqt中消息发送一致
第二个参数为传参,将需要处理的数据发送过去

this.$emit("delete", this.index)

B、父组件定义监听函数

定义监听消息名称及绑定的处理函数

@delete="handleDelete"

C、子组件传递了参数,在父组件的函数中需要单独写接收参数动作,否者参数未定义

handleDelete:function (index) {
                    this.list.splice(index, 1)
                }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue学习</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="root">
        <div v-if="show">hello</div>
        <input v-model="inputValue"/>
        <button @click="handleClick">click</button>
        <ul>
            <todo-item v-for="(item, index) of list"
                       :key="index"
                       :content="item"
                       :index="index"
                       @delete="handleDelete"
            >            </todo-item>
        </ul>
    </div>
    <script>
        Vue.component('todo-item',{
            props:['content', 'index'],
            template:'<li @click="handleClickS">{{content}} {{index}}</li>',
            methods:{
                handleClickS:function () {
                    this.$emit('delete', this.index)
                }
            }
        })
        new Vue({
            el:"#root",
            data:{
                show:true,
                inputValue:'',
                list:[]
            },
            methods:{
                handleClick:function () {
                    this.list.push(this.inputValue);
                    this.inputValue = "";
                },
                handleDelete:function (index) {
                    this.list.splice(index, 1)
                }
            },
        })
    </script>
</body>
</html>

相关文章

网友评论

      本文标题:【Vue.js】 todolist删除功能实现(十)

      本文链接:https://www.haomeiwen.com/subject/zjxvwftx.html