vue组件实例

<!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>组件基础</title>
</head>
<body>
    <div id="app">
        <my-father></my-father>
    </div>

    <template id="son">
        <div>
            <h1>my-son</h1>
            <h3>{{ title }}</h3>
            <button @click="test">test $emit()</button>
        </div>
    </template>
    <template id="father">
        <div>
            <h1>my-father</h1>
            <!-- 监听子组件发射的 test 事件 -->
            <my-son title="test props" @test="test"></my-son>
        </div>
    </template>

    <script src="https://vuejs.org/js/vue.js"></script>
    <script>
    
        // 一 、新建组件
        // 使用组件的第一步就是新建组件
        // 全局组件 :使用 Vue.component() 新建的组件是全局组件
        // 局部组件 :使用 components 属性挂载子组件
        // Vue.extend() :可以新建一个组件对象

        // 二 、组件的复用
        // 组件的 data 必须是一个函数
        // 因为组件复用时使用的是同一个组件实例 ,如果 data 作为一个引用类型的值的话 ,所有的组件将引用同一个 data

        // 三 、props 自定义组件特性
        // props 属性可以为组件自定义特性
        // 当一个值传递给一个 prop 特性的时候 ,它就会变成组件实例的一个属性

        // 四 、根元素
        // 每个组件只能拥有一个根元素

        // 五 、监听子组件事件
        // 组件可以使用 $emit() 方法发射一个事件 ,然后在父组件中监听这个事件

        // 六 、组件名大小写
        // 定义组件名的方式有两种
        // 使用 kebab-case :Vue.component('my-component-name', { /*  */ })
        // 使用 PascalCase :Vue.component('MyComponentName', { /*  */ })
        // 不管组件名使用的是 kebab-case 还是 PascalCase ,对应的标签名都是 <my-component-name>

        // 第一步 :新建一个 my-son 组件对象
        let MySon = Vue.extend({
            template: '#son',
            // 第四步 :自定义组件特性
            // 使用子组件的时候就可以使用 v-bind 为特性设置值了
            props: ['title'],
            methods: {
                test(){
                    // 发射一个 test 事件
                    this.$emit('test')
                }
            }
        })

        // 第二步 :新建一个 my-father 全局组件
        Vue.component('my-father', {
            template: '#father',
            // 第三步 :使用 components 属性挂载子组件
            components: {
                MySon
            },
            methods: {
                test(){
                    alert('说点什么好呢')
                }
            }
        })

        // 第三步 :定义根组件
        new Vue({
            
        }).$mount('#app')

    </script>

</body>
</html>

posted on 2021-04-20 16:30 青蛙學堂 阅读(148) 评论(0)  编辑 收藏 引用 所属分类: JavaScript

只有注册用户登录后才能发表评论。
<2006年2月>
2930311234
567891011
12131415161718
19202122232425
2627281234
567891011

导航

统计

常用链接

留言簿(8)

随笔分类

随笔档案

收藏夹

青蛙学堂

最新评论

阅读排行榜

评论排行榜