Vue单文件组件

创建两个基本组件

School组件

<template>
<div>
<h1>学校名称:{{ name }}</h1>
<h1>学校地址:{{ age }}</h1>
<button @click="showName"></button>
</div>
</template>
<script>
export default {
name: "Student",
data() {
return {
name: "刘绍基额",
age: 20,
};
},
methods: {
showName(){
alert(this.name);
}
},
};
</script>

Student组件

<template>
<div id="school">
<h1>学校名称:{{ name }}</h1>
<h1>学校地址:{{ address }}</h1>
</div>
</template>
<script>
//组件的默认暴露
export default { //原先是Vue.extend(options),但Vue会自动帮我们调用这个方法
data() {
return {
name: "lin",
address: "江西",
};
},
};
</script>
<style>
#school{
background-color: #bfa;
}
</style>

创建管理所有组件的组件App

<template>
<div>
<School />
<Student/>
</div>
</template>
<script>
//引入组件
import School from "./School.vue"; //加不加后缀都可以
import Student from "./Student.vue";
export default {
name: "App",
components: {
School,
Student,
},
};
</script>
<style>
</style>

创建vue实例

import App from './App.vue'
new Vue({
el: '#root',
components: {
App
}
})

创建根结构

<!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></App>
</div>
<!-- 由于main.js中使用了Vue,所以需要提前引入Vue依赖,这是一切的根 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="./main.js"></script>
</body>
</html>

现在还不能运行,因为浏览器并不支持.vue后缀的文件,我们需要vue脚手架(vue-cli)

posted @   小罗要有出息  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示