vue组件编写形成过滤效果

124 阅读1分钟

<script>
        Vue.component('my-menu', {
            props: {
                activeIndex: {
                    type: Number,
                    default: 0
                },
                list: {
                    type: Array,
                    required: true
                },
                label: {
                    type: String,
                    required: true
                }
            },
            data() {
                return {
                    index: this.activeIndex
                }
            },
            watch: {
                index(val) {
                    this.$emit("change", val)
                }
            },
            template: `
            <ul class="list">
                {{label}}:
                <li @click="index=i" :class="{active:i===index}" v-for="(item,i) in list">
                    {{item.name}}
                </li>
            </ul>
            `
        })
        let vm = new Vue({
            el: "#app",
            data() {
                return {
                    index1: 0,
                    index2: 0,
                    list: [
                        { id: 1, name: "巧克力" },
                        { id: 2, name: "蛋糕" }, 
                       { id: 3, name: "冰淇淋" },
                    ],
                    list1: [
                        { id: 1, name: "抹茶" },
                        { id: 2, name: "酸辣" },
                        { id: 3, name: "绿茶" },
                    ]
                }
            },
            methods: {
            }
        })
    </script>

将html中的内容放入template再监听获取形成过滤的效果

HTML

<div id="app" v-cloak>
        {{index1}} ---
        {{index2}}
        <my-menu :list="list" label='类型' @change="index1=$event"></my-menu>
        <my-menu :list="list1" label='口味' @change="index2=$event"></my-menu>
</div>

css

<style>
        li {
            display: inline-block;
            border: 1px solid orange;
            color: orange;
            padding: 10px 20px;
            margin: 0 10px;
            cursor: pointer;
            text-align: center;
            opacity: .5;
        }
        .active {
            opacity: 1;
            border: 1px solid orangered;
            color: orangered;
        }
    </style>