Vue中的组件实战

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/chengqiuming/article/details/102760359

一 代码

<!DOCTYPE html>
<html>


<head>
    <meta charset="utf-8">
    <title>TodoList</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>


<body>
    <!-- 挂载点 -->
    <div id="root">
        <div>
            <input v-model="item" />
            <button @click="handleadd">提交</button>
        </div>
        <ul>
            <!-- 使用组件,通过:content和index设置组件属性,将数据传递给子组件 -->
            <todo-item
                v-for="(item,index) of items"
                :key="index"
                :content="item"
                :index="index"
                @delete="handledel">
            </todo-item>
        </ul>
    </div>


    <script type="text/javascript">
        // 全局组件
        Vue.component('todo-item',{
            props: ['content', 'index'], // 组件的属性,通过props接受父组件传递的数据
            template: '<li @click="onDelete" >{{content}}</li>', // 组件模板
            methods: {
                onDelete: function () {
                    this.$emit('delete', this.index)    //触发delete事件,并将index数据传递给父组件
                }
            }
        })
        // 局部组件
        // var TodoItem = {
        //  template: '<li>{{content}} <span @click="onDelete" style="background:gray; color:white">x</span></li>', // 组件模板
        // }


        // 实例,Vue实例就是一个组件
        new Vue({
            el: "#root",
            // components: {
            //  'todo-item': TodoItem, // 注册局部组件到vue实例
            // },
            data: {
                item: "",
                items: []
            },
            methods: {
                handleadd: function () {
                    this.items.push(this.item);
                    this.item = ''
                },
                handledel: function (index) {
                    this.items.splice(index, 1)
                }
            }
        })
    </script>
</body>


</html>

二 效果

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/102760359