vue 基礎入門筆記 12:元件切換

September發表於2019-08-16
  • component 元件佔位符 :is 設定要渲染的元件
<!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>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
    <div id="app">
        <div role="tabpanel">
            <!-- Nav tabs -->
            <ul class="nav nav-tabs" role="tablist">
                <li role="presentation" class="active">
                    //點選不同tab  切換不同元件
                    <a href="#home" @click.prevent="componentName = 'tabpanel1'" aria-controls="home" role="tab"
                        data-toggle="tab">home</a>
                </li>
                <li role="presentation">
                    <a href="#tab" @click.prevent="componentName = 'tabpanel2'" aria-controls="tab" role="tab"
                        data-toggle="tab">tab</a>
                </li>
            </ul>
            <!-- Tab panes -->
            <div class="tab-content">
            </div>
            //元件佔位符  
            <component :is="componentName"></component>
        </div>
    </div>
    <template id="tab1">
        <h1>tab1</h1>
    </template>
    <template id="tab2">
        <h1>tab2</h1>
    </template>
    <script>
        //定義兩個元件
        Vue.component('tabpanel1', {
            template: '#tab1'
        })
        Vue.component('tabpanel2', {
            template: '#tab2'
        })
        var vm = new Vue({
            el: '#app',
            data: {
                //預設指向第一個元件
                componentName: 'tabpanel1'
            },
            methods: {}
        });
        Vue.config.devtools = true
    </script>
</body>

</html>
本作品採用《CC 協議》,轉載必須註明作者和本文連結
日照香爐生紫煙

相關文章