单页组件就是使用Vue脚手架创建的以vue为后缀的单页文件。
其基本结构为:
<template> <div>单页组件</div> </template> <script> export default { data () { return {} }, methods: {} } </script> <style lang="less" scoped="scoped"> </style>首先在src/components/static目录下创建一个单页组件,下面以IndexNav.vue为例
<template> <ul style="border: 1px solid #EEEEEE;"> <li v-for="(item, index) in categoryList" :key="index" class="li-category"> <router-link :to="{path: '/tags', query: {name: item}}">{{item}}</router-link> </li> </ul> </template> <script> export default { data () { return { // 分类专栏列表【从数据库中获取】 categoryList: ['CSS', 'HTML', 'JavaScript', 'Java', 'C', 'C++', 'Python', 'C#', 'Spring'] } } } </script> <style lang="less" scoped="scoped"> ul { padding: 0; margin: 0; text-align: center; background: #fff; } .li-category { list-style: none; display: block; padding: 3px 8px; margin: 2px; a { text-decoration: none; color: #000; } } .li-category:hover { background: rgb(249,216,214); border-radius: 5px; a { color: red; } } </style>这是一个完整的单页vue,显示浏览如下
一般使用这种vue文件是通过路由跳转直接显示的,但是有些组件,如侧边栏、搜索导航在多个页面都有使用,不可能每个页面都去复制粘贴一样的代码,所以有组件的复用,而vue提供的是直接在另一个组件内部写template等进行设置,不属于一个完整的单页组件。
接着在根目录下的main.js中引入组件并进行全局注册
其中IndexNav是引入的组件名称,而'blog-index-nav'是自定义的组件名称,是在其他地方进行引用的。
注册成功后,就可以在其他vue页面中进行引用
组件复用成功
创建一个vue单页组件,该组件是子组件
<template> <el-card> <div slot="header" class="clearfix"> <span style="font-weight: bold;">{{title}}</span> <div v-for="(item, index) in data" :key="index" class="item"> <el-row> <el-col :span="8"> <el-image style="width: 60px; height: 40px" :src="require('../../assets/images/' + item.image)" fit="contain"></el-image> </el-col> <el-col :span="8"> <el-link style="height: 40px;line-height: 40px;font-size: 20px;">{{item.category}}</el-link> </el-col> <el-col :span="8"> <span style="height: 40px;line-height: 40px;color:#D7D7D7;font-size: 16px;">{{item.eassyCount}}</span> </el-col> </el-row> </div> </div> </el-card> </template> <script> export default { name: 'CardComponent', // 组件的名称 props: { // 组件要传递的参数 title: String, // 参数1:title,字符串类型 data: Array // 参数2:data,数组类型 } } </script> <style lang="less" scoped="scoped"> .text { font-size: 14px; } .item { margin-bottom: 18px; } .clearfix:before, .clearfix:after { display: table; content: ""; } .clearfix:after { clear: both } .box-card { width: 480px; } </style>把需要引入的vue文件中引入,该组件是父组件