文章目录
一、什么是组件?
组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以表现为用 is 特性进行了扩展的原生 HTML 元素。所有的 Vue 组件同时也都是 Vue 的实例,所以可接受相同的选项对象 (除了一些根级特有的选项) 并提供相同的生命周期钩子。总而言之,使用组件的原因,大部分是因为代码的重复使用等等。
二、新建导航栏Navigation.vue文件
在src目录下,新建component文件夹,然后在component文件夹下,新建Navigation.vue
注:该文件用于测试
<template>
<!-- 该文件应该在在src/component目录下,如果没有component目录则,新建component文件夹,然后在component文件夹下,新建Navigation.vue -->
<div>
<ul>
<li>vue</li>
<li>java</li>
</ul>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
三、新建首页Index.vue文件
在src目录下,新建views文件夹,然后在views文件夹下,新建Index.vue文件
<template>
<div id="app">
<v-nav></v-nav><!-- v-nav 应该与下面script中的import vNav from ....中的vNav字母一致,但是应该为小写 -->
</div>
</template>
<!-- js -->
<script>
import vNav from '../component/Navigation.vue'
export default {
components:{
vNav
}
}
</script>
<!-- css -->
<style>
</style>
四、新建路由routes.js文件
在src目录下,新建router文件夹,然后在router文件夹下,新建routes.js文件
import index from '../views/Index.vue' // 引入Index.vue页面
let routes = [
{
path:'/index', // 请求uri
component:index, // 指定Index.vue页面
name:'首页', // Index.vue页面的名称
hidden:true
}
];
export default routes;
五、修改App.vue文件
<template>
<div id="app">
<router-view></router-view> <!-- 引入路由 -->
</div>
</template>
<script>
export default {
methods: {
startHacking () {
this.$notify({
title: 'It works!',
type: 'success',
message: 'We\'ve laid the ground work for you. It\'s time for you to build something epic!',
duration: 5000
})
}
}
}
</script>
<style>
#app {
font-family: Helvetica, sans-serif;
text-align: center;
}
</style>
六、修改main.js文件
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'
import vueRouter from 'vue-router' // 引入vue路由
import routes from './router/routes.js' // 引入自己的路由js
Vue.use(ElementUI)
Vue.use(vueRouter) // 使用vueRouter
// 实例化router对象
const router = new vueRouter({
routes,
mode:'history' // 可以取消在浏览器地址栏中输入#
})
new Vue({
router, // 添加路由对象
el: '#app',
render: h => h(App)
})
七、运行测试
请参照Element入门案例(Hello World!)的第七节 :https://blog.csdn.net/qq_40790831/article/details/88138538