Vue组件化编程(单文件组件)
单文件组件
School.vue
<template> <div class="demo"> <h2>学校名称:{ { schoolName}}</h2> <h2>学校地址:{ { address}}</h2> <button @click="showName">点我提示学校名</button> </div> </template> <script> export default { name:School, data() { return { schoolName:尚硅谷, address:北京昌平 } }, methods: { showName() { alert(this.showName) } }, } </script> <style> .demo { background-color: orange; } </style>
Student.vue
<template> <div> <h2>学生姓名:{ { name}}</h2> <h2>学生年龄:{ { age}}</h2> <button @click="showName">点我提示学生名</button> </div> </template> <script> export default { name:Student, data() { return { name:张三, age:18 } }, methods: { showName() { alert(this.name) } }, } </script> <style> </style>
App.vue
<template> <div> <school></school> <student></student> </div> </template> <script> // 第一步:引入组件 import School from ./School import Student from ./Student export default { name:App, // 第二步:注册组件 components:{ School, Student } }; </script> <style> </style>
main.js
import App from ./App.vue new Vue({ el:#root, components:{ App } })
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>练习一下单文件组件的语法</title> </head> <body> <div id="root"> <app></app> </div> <script type="text/javascript" src="../js/vue.js"></script> <script type="text/javascript" src="./main.js"></script> </body> </html>
说明:
-
1、先定义两个组件:School.vue 和 Student.vue 2、将这两个组件汇总到一起也就是App.vue 组件里面 3、那么将这个 App.vue 组件引入到 创建 Vue 实例的 main.js 文件中 4、最后创建 index.html 文件