【110】Vue2利用父子路由實現標籤頁切換,並且支持瀏覽器回退。

源代碼倉庫: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 可在碼雲中查看。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章