最近有时间学习vue.js,什么是vue.js,就不在此叙述,官网为 vue.js官网
直接进入主题:
1. 使用webpack进行vue.js项目搭建
首先要安装webpack工具,要全局安装:
# 全局安装 webpack
$ npm install webpack -g
# 全局安装 vue-cli
$ npm install --global vue-cli
# 创建一个基于 webpack 模板的新项目
$ vue init webpack my-project
# 安装依赖,走你
$ cd my-project
$ npm install
$ npm run dev
这样,就创建好了一个基本的vue.js的项目。默认端口为8080,在本机上访问http://localhost:8080即可看到主页面。
- 使用vue-router插件实现路由功能
进入到my-project目录下,使用以下命令进行安装vue-router插件安装
$ npm install vue-router –save-dev
此处需要添加 —save-dev 的原因,是把此插件包安装到当前目录下的node_modules下,且把相关的安装信息添加到package.json文件的devDependencies字段里,方便包管理。(1) 在src目录下,新建routers.js文件,并添加以下内容
export default {
'/': 'Home',
'/about': 'About',
'/svg': 'Svg'
}
(2) src中添加pages目录,用以存放页面文件
(3) 在main.js中代码修改如下
import Vue from 'vue'
import routes from './routes'
const app = new Vue({
el: '#app',
data: {
currentRoute: window.location.pathname
},
computed: {
ViewComponent () {
const matchingView = routes[this.currentRoute]
return matchingView
? require('./pages/' + matchingView + '.vue')
: require('./pages/404.vue')
}
},
render (h) {
return h(this.ViewComponent)
}
})
window.addEventListener('popstate', () => {
app.currentRoute = window.location.pathname
})
(4) src中添加layouts目录,用以存放页面综合布局页面。
(5) pages文件夹下新建Home.vue文件,代码如下:
<template>
<main-layout>
<p>Welcome home</p>
</main-layout>
</template>
<script>
import MainLayout from '../layouts/Main.vue'
export default {
components: {
MainLayout
}
}
</script>
(6) layouts目录下新建main.vue文件,代码如下:
<template>
<div class="container">
<ul>
<li>
<v-link href="/">Home</v-link>
<v-link href="/about">About</v-link>
<v-link href="/svg">Svg</v-link>
</li>
</ul>
<slot></slot>
</div>
</template>
<script>
import VLink from '../components/VLink.vue'
export default {
components: {
VLink
}
}
</script>
<style scoped>
.container {
max-width: 700px;
min-height: 800px;
margin: 0 auto;
padding: 15px 30px;
background: #f9f7f5;
}
</style>
(7) components目录下新建VLink.vue文件,代码如下:
<template>
<a
v-bind:href="href"
v-bind:class="{ active: isActive }"
v-on:click="go"
>
<slot></slot>
</a>
</template>
<script>
import routes from '../routes'
export default {
props: {
href: String,
required: true
},
computed: {
isActive () {
return this.href === this.$root.currentRoute
}
},
methods: {
go (event) {
event.preventDefault()
this.$root.currentRoute = this.href
window.history.pushState(
null,
routes[this.href],
this.href
)
}
}
}
</script>
<style scoped>
.active {
color: cornflowerblue;
}
</style>
(8) 至此,根目录下运行npm run dev 命令即可项目启动,并自动在浏览器中打开http://localhost:8080页面,即可看到效果,如下:
项目演示地址:http://dw.webshao.com/
github项目地址:https://github.com/Garens/vue