华域联盟 JavaScript Vue之组件详解

Vue之组件详解

文章目录[隐藏]

<body>
    <div id="root">
        <h2>{{name}}</h2>
        <hr>
        <school></school>
        <hr>
        <student></student>
        <hr>
        <!-- <h2>学生姓名:{{name}}</h2>
        <h2>学生年龄:{{age}}</h2> -->
    </div>
    <div id="root2">
        <hello></hello>
    </div>
    <script>
        Vue.config.productionTip = false;
        //创建school组件
        //el:'#root'
        //组件定义时 一定不要写el配置项,因为最终所有的组件都要被一个vm管理 由vm决定服务于哪个容器
        const school = Vue.extend({
            template: `
            <div>
                <h2>学校名称:{{schoolName}}</h2>
                <h2>学校地址:{{address}}</h2>
               <button @click="showName">点我提示学校名称</button>
                </div>
           `,
            data() {
                return {
                    schoolName: '二中',
                    address: '北京',
                }
            },
            methods: {
                showName() {
                    alert(this.schoolName)
                }
            }
        })
        //第一步:创建组件
        //创建学生组件
        const student = Vue.extend({
            template: `
         <div>  
        <h2>学生姓名:{{name}}</h2>
        <h2>学生年龄:{{age}}</h2>
        </div>
           `,
            data() {
                return {
                    name: '小王',
                    age: 20,
                }
            }
        })
        //创建vm
        new Vue({
            el: '#root',
            data: {
                name: '你好,世界!'
            },
            //第二步:注册组件(局部注册)
            components: {
                school,
                student
            }
        })

        const hello = Vue.extend({
            template: `
            <div><h2>你好鸭!王同学</h2></div>
            `
        })
        Vue.component('hello', hello)
        new Vue({
            el: '#root2'
        })
    </script>
</body>

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注华域联盟的更多内容!

本文由 华域联盟 原创撰写:华域联盟 » Vue之组件详解

转载请保留出处和原文链接:https://www.cnhackhy.com/147309.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们