Vue中的組件實戰

一 代碼

<!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>

二 效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章