27_动态组件

2018-02-11  本文已影响0人  CHENPEIHUANG
<!DOCTYPE html>
<html lang="zh">
<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>
</head>
<body>
    <div id="app">
        <!--使用v-bind将变量绑定数据,数据更改,变量也更改-->
        <!--动态组件:使用is属性来绑定变量,控制变量的值使当前元素动态渲染不同的组件-->
        <p>
            <a href="#" @click.stop="which='home'">主页</a>
            <a href="#" @click.stop="which='about'">介绍</a>
        </p>
        <div :is="which"></div>
    </div>
    <script src="js/vue.js"></script>
    <script>
        //const定义的变量不可以修改,而且必须初始化
        //var定义的变量可以修改,如果不初始化会输出undefined,不会报错。
        const Home = {
            template:"<div><h1>主页</h1><p>主页内容。。。。</p></div>"
        }
        const About = {
            template:"<div><h1>介绍</h1><p>介绍内容。。。。</p></div>"
        }
        var vm = new Vue({
            el:"#app",
            components:{
                'home':Home,
                'about':About
            },
            data:{
                which:"home"
            }
        })
    </script>
</body>
</html>

也可将template单独拿出来

<!DOCTYPE html>
<html lang="zh">
<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>
</head>
<body>
    <div id="app">
        <p>
            <a href="#" @click="which='home'">主页</a>
            <a href="#" @click="which='about'">介绍</a>
        </p>
        <div :is="which"></div>
    </div>
    <script src="js/vue.js"></script>
    <script type="x-template" id="tit">
        <div>
            <h1>主页</h1>
            <p>主页内容。。。。</p>
        </div>
    </script>
    <script type="x-template" id="content">
        <div>
            <h1>介绍</h1>
            <p>介绍内容。。。。</p>
        </div>
    </script>
    <script>
        const Home = {
            template:"#tit"
        }
        const About = {
            template:"#content"
        }
        
        var vm = new Vue({
            el:"#app",
            components:{
                'home':Home,
                'about':About
            },
            data:{
                which:'home'
            }
        })
    </script>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读