创新项目实训(三)
在完成了所需要的框架等的安装与配置后,就要开始使用Vue写前端了。
在Vue中一个非常重要的概念就是组件系统了。组件系统是一种抽象,允许我们使用小型、独立和通常可复用的组件构建大型应用,几乎任意类型的应用界面都可以抽象为一个组件树。因此,要用好vue,就要好好掌握组件这一概念。
根据官方文档,在 Vue 里,一个组件本质上是一个拥有预定义选项的一个 Vue 实例。也就是说,它和页面一样,都可以写在**.vue**文件中,然后在需要的地方进行引用。这里贴一个导航栏组件的代码。
<template>
<el-menu
:default-active="activeIndex"
class="NavBar"
mode="horizontal"
@select="handleSelect"
>
<el-menu-item index="1">
<a href="#/ticket">火车票&机票</a>
</el-menu-item>
<el-menu-item index="2">
<a href="#/hotel">酒店查询</a>
</el-menu-item>
<el-menu-item index="3">
<a href="#/schedule">行程推荐</a>
</el-menu-item>
<el-menu-item index="4">
<a href="#/discount">优惠搜索</a>
</el-menu-item>
</el-menu>
</template>
<script>
export default {
data() {
return {
activeIndex: "1",
activeIndex2: "1",
};
},
methods: {
handleSelect(key, keyPath) {
console.log(key, keyPath);
},
},
};
</script>
<style scoped>
a {
text-decoration: none;
}
</style>
这样就完成了一个组件的编写。
组件的调用也很简单,调用时只需要在页面的 < script > 标签中先导入该类,在components属性中为该类定义一个自定义标签,就可以在此页面上使用标签调用该组件了。此处是我使用上面导航栏组件的例子。由于该导航栏需要在所有页面中出现,因此我将其放在了App.vue文件中。
<template>
<div id="app">
<navbar></navbar>
<router-view></router-view>
</div>
</template>
<script>
import NavBar from './components/NavBar.vue'
export default {
name: 'app',
components:{
'navbar':NavBar
}
}
</script>
<style scoped>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
使用组件有一个非常大的好处就是在很多地方需要同一个(或基本类似)的元素时可以很方便地进行复用,无需复制代码。而在我们的项目中,有很多地方都可以使用组件,例如显示搜索到的多条内容时,可以定义一个组件,让所有内容都按照同一样式显示,可以减少重复的代码量,使代码更可读。