一.vue-cli构建工具
目前,我们在搭建前端项目的时候,都会用到webpack来进行操作的,但是单纯的手动自己搭建一个webpack耗费的,因此我们可以借助官方提供的vue-cli来进行vue的快速搭建。
①安装npm,此处需要安装node.js
说到npm,这里提及一下cnpm,cnpm是淘宝团队提供的npm镜像服务,每十分钟与npm同步更新一次,因此同步性很好,基本保持着内容一致,如果由于网络问题,可以考虑用cnpm代替npm进行使用。
安装cnpm,npm install -g cnpm --registry=https:
//registry.npm.taobao.org
②安装vue-cli ,以及项目创建操作
全局安装:npm install --global vue-cli
vue-cli版本查询:vue -V(对vue-cli进行版本查询)
新建项目:vue init webpack projectname
安装项目阶段:记住项目名需要小写(其它可以直接选择enter就行)
二. vue路由
vue自身给我们提供了路由vue-router插件,也可以独自开发一个路由,但是考虑的方面有很多。
上述我们已经安装了vue-cli,且用来创建了一个项目,在创建项目的时候,会有提示我们是否进行路由的安装,那里我们要选择Y来进行确认就可以了。
路由配置,我们可以在需要的文件中进行路由的设置,这里我们在main.js中进行路由的设置,如果在其它文件中设定,导出需要的路由就可以了。
首先创建三个组件页面:indexOne.vue, indexTwo.vue,indexThree.vue
indexOne.vue
<template>
<div>
<h1>indexOne</h1>
<router-link to="/indexTwo">跳转到 indexTwo</router-link>
</div>
</template>
<script>
export default {
}
</script>
indexTwo.vue
<template>
<div>
<h1>indexTwo</h1>
<button @click="handleRouter">跳转到 indexThree</button>
</div>
</template>
<script>
export default {
methods: {
handleRouter () {
this.$router.push('/indexThree/1');
}
}
}
</script>
indexThree.vue
<template>
<div>{{ $route.params.id }}</div>
</template>
<script>
export default {
mounted () {
console.log(this.$route);
}
}
</script>
main.js
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const Routers = [
{
path: '/indexOne',
meta: {
title: 'indexOne'
},
component: (resolve) => require(['./views/indexOne.vue'], resolve)
},
{
path: '/indexTwo',
meta: {
title: 'indexTwo'
},
component: (resolve) => require(['./views/indexTwo.vue'], resolve)
},
{
path: '/indexThree/:id',
meta: {
title: 'indexThree'
},
component: (resolve) => require(['./views/indexThree.vue'], resolve)
},
{
path: '*',
redirect: '/index'
}
];
const RouterConfig = {
mode: 'history',//开启history模式,将所有路由都指向同一个html,或设置404页面为html
routes: Routers
};
const router = new VueRouter(RouterConfig);
//设置导航钩子,此钩子会在改变前触发,故在里面进行页面标题的变化。
//参数:to,表示即将要进入的目标的路由对象。
//参数:from,当前导航即将要离开的路由对象。
//参数:next,调用该方法后,才能进入下一个钩子。
router.beforeEach((to, from, next) => {
window.document.title = to.meta.title;
next();
});
new Vue({
el: '#app',
router: router,
render: h => {
return h(App)
}
});
以上就为vue-router的简单配置,其中要对webpack-dev-server进行支持History路由,在package.json中修改dev命令:
"scripts": {
"dev": "webpack-dev-server --open --history-api-fallback --configwebpack.config.js",
},