不使用Node.js, npm, webpack 等, 在静态页中使用vue.js. 包括路由, 单文件组件. 

 

1. 创建index.html

index.html做为项目的首页, 主要用来定义页面框架, 加载必需的css和script.

这里使用element-ui的导航菜单组件搭建了一个页面框架.

需要注意的是, <el-menu> 标签要加上 :default-active="$route.path" 和 @select="handleSelect"; 有了这两个属性才能实现路由的跳转.

在菜单项<el-meun-item>标签中要加上index="menu-2-index"属性, 意思就是当前菜单对应的路由.

最后不要忘记"<router-view></router-view>". vue 组件将会被填充的这里.

script主要引用的有vue和vue-router以及element-ui, ajax请求使用的是axios, 如果不喜欢可以更换为jQuery等.

<!DOCTYPE html>
<html lang="en" xmlns:th="http:www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<title>Vue Test</title>
</head>
<body>
<div id="app">
<el-container>
<el-aside width="200px">
<el-menu :default-openeds="['1']" :default-active="$route.path" @select="handleSelect">
<el-menu-item index="">
<template slot="title"><i></i>菜单1</template>
</el-menu-item>
<el-menu-item index="/menu-2-index">
<template slot="title"><i></i>菜单2</template>
</el-menu-item>
<el-menu-item index="/menu-3-index">
<template slot="title"><i></i>菜单3</template>
</el-menu-item>
</el-menu>
</el-aside>
<el-container>
<router-view></router-view>
</el-container>
</el-container>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js "></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="./js/util.js"></script>
<script src="./js/route.js"></script>
<script src="./js/main.js"></script>
</body>
</html>


 

2. 创建单文件组件

单文件组件格式与 Vue 官网实例一致, HTML片段必须使用<template>标签包括.

<template>
<div id="menu1">
<h1>Hello Menu 1</h1>
<h2>{{message}}</h2>
</div>
</template>

<script>
exports = {
data: function () {
return {
message: 'Hello Vue!'
}
}
}
</script>

<style>
#menu1 {
font-size: 12px;
}
</style>


 

3. 定义路由配置

组件的加载使用异步方式, util.loadComponent(url), 此方法中传入服务器url, 接收服务器返回的单文件组件, 即HTML片段.

var routes = [{
path: '/menu-1-index',
name: 'menu-1-index',
component: util.loadComponent('../views/menu1.html')
}, {
path: '/menu-2-index',
name: 'menu-2-index',
component: util.loadComponent('./views/menu2.html')
}];

var router = new VueRouter({
routes: routes
});


4. 定义main.js

在Vue实例中绑定路由, 并实现handleSelect方法, 用于路由的跳转.

var app = new Vue({
el: '#app',
router : router,
data: function () {
return {
activeIndex:1,
}
},
methods: {
handleSelect : function(key, path) {
console.log(key, path)
this.$router.push(key)
}
}
});