Blog of CodeJELLOW’S ENGINEERING NOTES
← 返回文章

VUE3(十)组件化开发

VUE3(十)组件化开发 全局组件 局部组件 开发模式

全局组件

编写一个全局组件如同编写传给Vue.createApp()方法的参数一样,需要传入一个含有options的对象,同样有template、data、methods等选项。

注册一个组件的方法是,获取了Vue.createApp()的实例之后,调用component方法,第一个参数是组件名称,第二个就是创建的组件对象。

TEXT
    <template id="my-app">
        <component-a></component-a>
    </template>

    <template id="component-a">
        <h2>{{title}}</h2>
        <P>{{desc}}</P>
        <button @click="btnClick">按钮点击</button>
    </template>
    <script src="../js/vue.js"></script>
    <script>
        const app={
            template:"#my-app",
            data(){
                return{
                    message: "hello world"
                }
            },
            methods:{

            }
        };
        const App=Vue.createApp(app);
        // 使用app注册一个全局组件
        // 全局组件:意味着注册的这个组件可以在任何的组件模板中使用
        App.component("component-a",{
            template: "#component-a",
            data(){
                return {
                    title: "我是标题",
                    desc: "我是内容哈哈哈"
                }
            },
            methods: {
                btnClick(){
                    console.log("按钮发生了点击");
                }
            }
        });
        App.mount("#app")
    </script>

component的命名规则:在html中使用-来分割,在JavaScript中既可以使用-也可以使用大驼峰。

局部组件

局部组件需要在使用的组件中声明。声明方式是在要用到的组件中添加components属性,并以组件名-组件对象名的键值对定义。

TEXT
    <template id="my-app">
        <h2>{{message}}</h2>
        <component-a></component-a>
    </template>

    <template id="component-a">
        <h2>我是组件A</h2>
        <p>我是内容,哈哈哈</p>
    </template>

    <script src="../js/vue.js"></script>
    <script>
        const componentA={
            template: "#component-a"
        }
        const app={
            template:"#my-app",
            data(){
                return{
                    message: "hello world"
                }
            },
            components:{
                // key:组件名称
                // value:组件对象
                componentA: componentA
                // 语法糖可以只写value(因为一般情况下key和value相同)
            }
        };
        const App=Vue.createApp(app);

        App.mount("#app");
    </script>

VUE3开发模式

组件化开发通常会创建一个.vue的single-file components来管理某个组件,并使用webpack或vite等构建工具进行处理。

一个简单的例子:

TEXT
<template>
    <div>
        <h2>{{title}}</h2>
        <P>{{desc}}</P>
        <button @click="btnClick">按钮点击</button>
    </div>
</template>

    

<script>
export default {
    data(){
        return {
            title: "我是标题",
            desc: "我是内容哈哈哈"
        }
    },
    methods: {
        btnClick(){
            console.log("按钮发生了点击");
        }
    }
}
</script>

<style scoped>

</style>
通过 RSS 订阅更新 →