Vue学习之todolist删除功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue</title>
    <script src="vue.js"></script>
</head>
<body>

    <!-- todolist组件拆分 删除功能
        
        例如当
        <li v-for="(item, index) of list" :key="index">
                {{item}}
            </li>
        非常庞大或者复杂的时候,就可以才分出来进行维护

        Vue.component({})定义的组件成为全局组件

        var Todo-item 为局部组件,需要再vue中进行注册

        组件和实例之间的关系
        1、每个组件都是vue的一个实例
        2、父组件向子组件传值是通过属性的形式进行的
     -->

    <!-- 此为父组件模板 -->
    <div id="root">
        <div>
            <input v-model="inputValue" />
            <button @click="handleSubmit">提交</button>
        </div>
        <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="handleClick">{{content}}</li>',
            methods:{
                handleClick: function() {
                    //向外触发一个事件
                    this.$emit('delete', this.index)
                }
            }
        })

        // var TodoItem = {
        //     template: '<li>item</li>'
        // }

        //父组件
        new Vue({
            el:"#root",
            // components:{
            //     'todo-item': TodoItem
            // },
            data:{
                inputValue: 'hello',
                list: []
            },
            methods: {
                handleSubmit: function() {
                    this.list.push(this.inputValue)
                    this.inputValue = ''
                },
                handleDelete: function(index){
                    this.list.splice(index, 1)
                }
            }
        })
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/twodoge/p/10230342.html