这个才是动态组件的,只是这个写法比上一个写法好像看起来代码量多一点,忽略上一个提问中的忘记删除的警告信息的前题下

来源:4-16 自由编程

YoLo_H

2020-12-20 16:30:10

<!DOCTYPE html>

<html lang="en">


<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <script src="./vue.js"></script>

    <style>

        * {

            margin: 0;

            padding: 0;

        }


        .wrap {

            width: 390px;

            height: auto;

            margin: 0 auto;

            border: 1px solid grey;

            display: flex;

        }


        p {

            width: 130px;

            height: 100%;

            text-align: center;

        }


        .Center_P {

            margin: 20px auto;

        }


        .active {

            background-color: gray;

        }

    </style>

</head>


<body>

    <div id="app">

        <div class="wrap">

            <p v-for="(item,index) in list" :key="index" @click="hanDleClick(index)"

                :class="{active:index===listCurrentIndex?true:false}">

                {{ item }}

            </p>

        </div>

        <p-one v-if="type==='p-one'"></p-one>

        <p-two v-if="type==='p-two'"></p-two>

        <p-three v-if="type==='p-three'"></p-three>

    </div>

    <script>

        Vue.component('p-one', {

            template'<p class="Center_P">前端工程师</p>'

        })

        Vue.component('p-two', {

            template'<p class="Center_P">Java工程师</p>'

        })

        Vue.component('p-three', {

            template'<p class="Center_P">软件测试工程师</p>'

        })

        var vm = new Vue(

            {

                el"#app",

                data: {

                    list: ['前端工程师''Java工程师''软件测试工程师'],

                    type"p-one",

                    listCurrentIndex0,

                },

                methods: {

                    hanDleClickfunction (index) {

                        this.listCurrentIndex = index;

                        if (index == 0) {

                            this.type = "p-one";

                        }

                        else if (index == 1) {

                            this.type = "p-two";

                        }

                        else {

                            this.type = "p-three";

                        }

                    }

                }

            }

        )


    </script>

</body>


</html>


写回答

1回答

好帮手慕星星

2020-12-20

同学你好,这样写是动态组件,根据点击项选择对应的组件显示,没有问题,很棒哦。

上一个问题中虽然不是动态组件,但是实现了效果,不深究实现方式的话也可以。

祝学习愉快!

0

0 学习 · 10739 问题

查看课程