vue-router适用于单页面应用。
一、vue-router的引用方法
1、用script标签
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
2、npm安装
cnpm install vue-router
//在js文件引入
var Vue = require('vue')
var VueRouter = require('vue-router') Vue.use(VueRouter)
二、我的demo
1、package.json
{
"name": "vrouter",
"version": "1.0.0",
"description": "",
"main": "index.js",
"devDependencies": {
"vue": "^2.5.2",
"vue-router": "^3.0.1"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"server": "webpack-dev-server --open",
"build": "webpack-dev-server"
},
"author": "camille",
"license": "ISC"
}
2、webpack.config.js
module.exports = {
entry: './index.js',
output: {
path: __dirname,
filename: 'bundle.js'
},
devtool: "inline-source-map",
resolve: {
alias: {
'vue$': 'vue/dist/vue.js',
'vue-router$': 'vue-router/dist/vue-router.common.js'
}
}
}
3、index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>vue router</title>
<style type="text/css">
.router-link-active {
color: red;
}
</style>
</head>
<body>
<div id="J_vapp_router">
<div class="btn-box">
<button @click="login">登录</button>
<button @click="registe">注册</button>
</div>
<div class="tab-link">
<router-link to="/users/camille">个人中心</router-link>
<router-link to="/scanhistory">浏览记录</router-link>
</div>
<div class="content">
<router-view class="view one"></router-view>
<router-view class="view two" name="rv2"></router-view>
<router-view class="view three" name="rv3"></router-view>
</div>
</div>
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
注意:如果后面跟表达式,要写:to,如果是固定的字符串,可以直接写to。
4、index.js
var Vue = require('vue')
var VueRouter = require('vue-router') Vue.use(VueRouter)
// 定义(路由)组件
var rvc1 = { template: '<div>这是路由组件1{{ $route.params.id }}</div>' }
var rvc2 = { template: '<div>这是路由组件2</div>' }
var rvc3 = { template: '<div>这是路由组件3</div>' } // 定义路由
var routes = [
{
path: '/users/:id',
name: 'personcenter',
component: rvc1
},
{
path: '/scanhistory',
name: 'scanrecord',
components: {
default: rvc1,
rv2: rvc2,
rv3: rvc3
}
}
] // 创建router实例
var router = new VueRouter({
mode: 'history',
base: __dirname,
routes: routes
}) // 创建和挂载根实例
// 通过router配置参数注入路由,从而让整个应用都有路由功能。
var vappr = new Vue({
router: router,
methods:{
login: function(){
this.$router.push({ path: '/users/info', query: { plan: 'private' }})
},
registe: function(){
this.$router.push({ name: 'scanrecord', params: { userId: 123 }})
}
}
}).$mount('#J_vapp_router')