Vue 单文件组件

命名规则:

一个单词组成:

  1. school.vue
  2. School.vue(推荐)

多个单词组成

  1. my-school.vue
  2. MySchool.vue(推荐)


单文件中的三个元素:html、css、js

组件的结构:html

组件的交互:js

组件的样式:css


示例

<template>
    <!--  组件的结构  -->
    <div class="demo">
        <h3>学校:{{name}}</h3>
        <h3>地址:{{address}}</h3>
    </div>
</template>

<script>
    // 组件的交互
    export default {
        name: 'School', // 与文件名保持一致
        data() {
            return {
                name: 'ABC',
                address: '长沙'
            }
        }
    }
</script>

<style>
    /* 组件的样式 */
    .demo {
        background: antiquewhite;
    }
</style>


App.vue

单文件组件中使用 App 组件来管理所有组件

需要在 App 中,引入、注册、使用组件


示例

<template>
    <div>
    	<!--  使用组件  -->
        <School></School>
        <Student></Student>
    </div>
</template>

<script>
    // 引入组件
    import School from "./School.vue";
    import Student from "./Student.vue";

    export default {
        name: 'App',
        // 注册组件
        components: {
            School,
            Student
        }
    }
</script>


main.js

main.js 用来管理 App

需要引入并注册、使用 App 组件,使用 el 指定容器


示例

import App from "./App.vue";

new Vue({
    el: '#root',
    template:'<APP></APP>',
    components: {App}
})


index.html

在 index.html 中创建容器 <div id="root"></div>

导入 main.js 和 vue.js


示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div id="root"></div>
</body>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript" src="./main.js"></script>
</html>


posted @ 2022-04-27 11:50  春暖花开鸟  阅读(75)  评论(0编辑  收藏  举报