【110】Vue2利用父子路由實現標籤頁切換,並且支援瀏覽器回退。
阿新 • • 發佈:2019-01-01
用 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 可在碼雲中檢視。