在靜態頁面中使用 Vue.js
不使用
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 style="border: 1px solid #eee">
<el-aside width="200px" style="background-color: rgb(238, 241, 246)">
<el-menu :default-openeds="['1']" :default-active="$route.path" @select="handleSelect">
<el-menu-item index="">
<template slot="title"><i class="el-icon-message"></i>菜單1</template>
</el-menu-item>
<el-menu-item index="/menu-2-index">
<template slot="title"><i class="el-icon-menu"></i>菜單2</template>
</el-menu-item>
<el-menu-item index="/menu-3-index">
<template slot="title"><i class="el-icon-setting"></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)
}
}
});
可在附件中下載實例代碼: 附件