【110】Vue2利用父子路由实现标签页切换,并且支持浏览器回退。
源代码仓库:https://gitee.com/zhangchao19890805/csdnBlog.git用 git clone 克隆下这个项目后,blog110 文件夹里面就是这篇博文相关的源代码。项目依赖使用了yarn进行管理。文件目录结构:blog110│├─.babelrc├─.npmrc├─index.template.html├─packag...
·
源代码仓库:https://gitee.com/zhangchao19890805/csdnBlog.git
用 git clone
克隆下这个项目后,blog110 文件夹里面就是这篇博文相关的源代码。项目依赖使用了yarn进行管理。
文件目录结构:
blog110
│
├─.babelrc
├─.npmrc
├─index.template.html
├─package.json
├─webpack.config.js
├─yarn.lock
└─src
│
├─App.vue
├─home.vue
├─main.js
├─router.js
├─tabBtnList.js
├─tabBtnList.vue
└─tabContent.vue
源代码
App.vue
<template>
<div>
<router-view></router-view>
</div>
</template>
<script>
export default {
}
</script>
home.vue
<template>
<div>
首页<br/>
<router-link :to="{name:'tabBtnList'}">跳转到tab</router-link>
</div>
</template>
<script>
export default {
data(){
return {};
}
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import routes from './router'
import 'babel-polyfill';
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes
})
new Vue({
el: '#app',
router,
render: h => h(App)
})
router.js
import Home from './home.vue';
// import sonVue from "./son.vue";
export default [
{
path:'/',
name: "home",
component:Home
},
{
path: "/tabBtnList",
name: "tabBtnList",
component: ()=>import("./tabBtnList.vue"),
children:[
{
path: "tabContent/:tabId",
name: "tabContent",
component: ()=>import("./tabContent.vue")
}
]
}
]
tabBtnList.js
export default function getBtnList(){
return [
{id: "tab1", name: "标签1"},
{id: "tab2", name: "标签2"},
{id: "tab3", name: "标签3"}
];
}
tabBtnList.vue 这个文件是用来显示标签页按钮。为了当用户点击浏览器回退按钮时,tab按钮能够正常显示样式,特别增加了 beforeRouteUpdate
这一导航守卫。
在mounted 函数中,对初次进入和 F5 刷新也做了不同处理。初次进入使用 replace,可以避免回退的时候出现只有标签页按钮的情况。F5刷新时,获得tabId,然后改变对应tab按钮的样式。
tabBtnList.vue:
<template>
<div :class="classPrefix">
<template v-for="(item, index) in tabBtnList">
<span v-if="index > 0" style="padding: 5px;" :key="item.id+'white'"></span>
<span :key="item.id"
:class="selectedId==item.id ? classPrefix+'_active' : classPrefix+'_normal'"
@click="clickTabBtn(item)">{{item.name}}</span>
</template>
<router-view></router-view>
</div>
</template>
<script>
import getBtnList from "./tabBtnList";
export default {
data(){
return {
classPrefix: "blog109-tabBtnList_",
selectedId: "",
tabBtnList:[]
};
},
methods:{
clickTabBtn(item){
this.selectedId=item.id
this.$router.push({name: "tabContent", params:{tabId: this.selectedId} });
}
},
mounted(){
this.tabBtnList = getBtnList();
// F5刷新页面
if (this.$route.matched.some(r=>"tabContent"==r.name)) {
this.selectedId = this.$route.params.tabId;
} else { // 初次进入
this.selectedId = this.tabBtnList[0].id;
this.$router.replace({name: "tabContent", params:{tabId: this.selectedId} });
}
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
if (this.tabBtnList.length > 0) {
if (to.matched.some(r => "tabContent" == r.name)) {
this.selectedId = to.params.tabId;
}
}
next();
},
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
.blog109-tabBtnList_{
width: 600px;
margin: 10px auto 0 auto;
&_active{ color:blue;
padding: 0;
margin: 0;
border: 0;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: blue;
cursor: pointer;
}
&_normal{
color: rgb(37, 212, 139);
padding: 0;
margin: 0;
border: 0;
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: transparent;
cursor: pointer;
}
}
</style>
tabContent.vue
<template>
<div :class="classPrefix">
tabId: {{$route.params.tabId}}<br/>
我是标签页内容。我是标签页内容。我是标签页内容。我是标签页内容。我是标签页内容。我是标签页内容。我是标签页内容。我是标签页内容。
</div>
</template>
<script>
import getBtnList from "./tabBtnList";
export default {
data(){
return {
classPrefix: "blog109-tabContent_",
};
}
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
.blog109-tabContent_{
width: 600px;
}
</style>
配置文件
.babelrc
{
"presets": [
["latest", {
"es2016": { "modules": false }
}],
"stage-2"
]
}
.npmrc
sass_binary_site=https://npm.taobao.org/mirrors/node-sass/
phantomjs_cdnurl=https://npm.taobao.org/mirrors/phantomjs/
electron_mirror=https://npm.taobao.org/mirrors/electron/
registry=https://registry.npm.taobao.org
index.template.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>blog110</title>
</head>
<body>
<div id="app">
<router-view></router-view>
</div>
</body>
</html>
package.json
{
"name": "blog110",
"description": "CSDN blog110",
"version": "1.0.0",
"author": "",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot --port 8080",
"build": "rimraf dist && cross-env NODE_ENV=production webpack --progress --hide-modules"
},
"dependencies": {
"babel-polyfill": "^6.26.0",
"vue": "2.5.13",
"vue-router": "2.8.1"
},
"devDependencies": {
"babel-core": "6.26.0",
"babel-loader": "6.4.1",
"babel-preset-latest": "6.24.1",
"babel-preset-stage-2": "6.24.1",
"cross-env": "3.2.4",
"css-loader": "0.28.7",
"file-loader": "1.1.6",
"html-webpack-plugin": "2.30.1",
"node-sass": "4.7.2",
"rimraf": "2.6.2",
"sass-loader": "6.0.6",
"url-loader": "0.5.9",
"vue-loader": "13.6.1",
"vue-template-compiler": "2.5.13",
"webpack": "3.10.0",
"webpack-dev-server": "2.9.7"
}
}
webpack.config.js
var path = require('path')
var webpack = require('webpack')
const HTMLPlugin = require('html-webpack-plugin')
module.exports = {
entry: {
app: ['./src/main.js'],
// 把共用的库放到vendor.js里
vendor: [
'babel-polyfill',
'vue',
'vue-router'
]
},
output: {
path: path.resolve(__dirname, './dist'),
// 因为用到了 html-webpack-plugin 处理HTML文件。处理后的HTML文件都放到了
// dist文件夹里。html文件里面js的相对路径应该从使用 html-webpack-plugin 前
// 的'/dist/' 改成 '/'
publicPath: '/',
// publicPath: '/dist/',
filename: '[name].[hash].js'
// filename:'build.js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
}
// other vue-loader options go here
,preserveWhitespace: false
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
// font loader
{
test: /\.(ttf|eot|woff|svg)$/i,
loader: 'url-loader'
},
// 图片处理
{
test: /\.(png|jpg|gif)$/,
loader: 'url-loader',
options: {
limit: '1000',
name: '[name].[ext]?[hash]'
}
},
{
test: /\.(docx)$/,
loader: 'url-loader',
options: {
limit: '10',
name: '[name].[ext]'
}
}
// {
// test: /\.(png|jpg|gif|svg)$/,
// loader: 'file-loader',
// options: {
// name: '[name].[ext]?[hash]'
// }
// }
]
},
plugins:[
// 把共用的库放到vendor.js里
new webpack.optimize.CommonsChunkPlugin({name: 'vendor'}),
// 编译HTML。目的:在生产环境下,为了避免浏览器缓存,需要文件按照哈希值重命名。
// 这里编译可以自动更改每次编译后引用的js名称。
new HTMLPlugin({template: 'index.template.html'})
],
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
devServer: {
historyApiFallback: true,
noInfo: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
yarn.lock 可在码云中查看。
更多推荐
已为社区贡献12条内容
所有评论(0)