溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

好程序員web前端培訓(xùn)分享kbone高級(jí)-事件系統(tǒng)

發(fā)布時(shí)間:2020-08-09 13:27:05 來(lái)源:ITPUB博客 閱讀:129 作者:好程序員 欄目:web開發(fā)

  好程序員web前端培訓(xùn) 分享kbone 高級(jí) - 事件系統(tǒng):1 、用法, 對(duì)于多頁(yè)面的應(yīng)用,在 Web  端可以直接通過  標(biāo)簽或者  location  對(duì)象進(jìn)行跳轉(zhuǎn),但是在小程序中則行不通;同時(shí)  Web  端的頁(yè)面  url  實(shí)現(xiàn)和小程序頁(yè)面路由也是完全不一樣的,因此對(duì)于多頁(yè)開發(fā)最大的難點(diǎn)在于如何進(jìn)行頁(yè)面跳轉(zhuǎn)。

   1.1 修改 webpack 配置

   對(duì)于多頁(yè)應(yīng)用,此處和 Web 端一致,有多少個(gè)頁(yè)面就需要配置多少個(gè)入口文件。如下例子,這個(gè)應(yīng)用中包含 page1、page2 和 page2 三個(gè)頁(yè)面:

// webpack.mp.config.js

module.exports = {

  entry: {

    page1: path.resolve(__dirname, '../src/page1/main.mp.js'),

    page2: path.resolve(__dirname, '../src/page2/main.mp.js'),

    page3: path.resolve(__dirname, '../src/page3/main.mp.js'),

  },

  // ... other options

}

1.2 修改 webpack 插件配置

mp-webpack-plugin 這個(gè)插件的配置同樣需要調(diào)整,需要開發(fā)者提供各個(gè)頁(yè)面對(duì)應(yīng)的 url 給 kbone。

module.exports = {

  origin: 'https://test.miniprogram.com',

  entry: '/page1',

  router: {

    page1: ['/(home|page1)?', '/test/(home|page1)'],

    page2: ['/test/page2/:id'],

    page3: ['/test/page3/:id'],

  },

  // ... other options

}

其中 origin 即 window.location.origin 字段,使用 kbone 的應(yīng)用所有頁(yè)面必須同源,不同源的頁(yè)面禁止訪問。entry 頁(yè)面表示這個(gè)應(yīng)用的入口 url。router 配置則是各個(gè)頁(yè)面對(duì)應(yīng)的 url,可以看到每個(gè)頁(yè)面可能不止對(duì)應(yīng)一個(gè) url,而且這里的 url 支持參數(shù)配置。

有了以上幾個(gè)配置后,就可以在 kbone 內(nèi)使用 a 標(biāo)簽或者 location 對(duì)象進(jìn)行跳轉(zhuǎn)。kbone 會(huì)將要跳轉(zhuǎn)的 url 進(jìn)行解析,然后根據(jù)配置中的 origin 和 router 查找出對(duì)應(yīng)的頁(yè)面,然后拼出頁(yè)面在小程序中的路由,最后通過小程序 API 進(jìn)行跳轉(zhuǎn)(利用 wx.redirectTo 等方法)。

2、案例

 kbone-advanced 目錄下創(chuàng)建 02-mulpages 目錄。本案例在這個(gè)目錄下實(shí)現(xiàn)。

2.1 創(chuàng)建 package.json

cd 02-mulpages

npm init -y

編輯 package.json:

{

  "name": "01-env",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "mp": "cross-env NODE_ENV=production webpack --config build/webpack.mp.config.js --progress --hide-modules"

  },

  "dependencies": {

    "add": "^2.0.6",

    "vue": "^2.5.11"

  },

  "browserslist": [

    "> 1%",

    "last 2 versions",

    "not ie <= 8"

  ],

  "devDependencies": {

    "babel-core": "^6.26.0",

    "babel-loader": "^7.1.2",

    "babel-preset-env": "^1.6.0",

    "cross-env": "^5.0.5",

    "css-loader": "^0.28.7",

    "file-loader": "^1.1.4",

    "html-webpack-plugin": "^4.0.0-beta.5",

    "mini-css-extract-plugin": "^0.5.0",

    "optimize-css-assets-webpack-plugin": "^5.0.1",

    "stylehacks": "^4.0.3",

    "vue-loader": "^15.7.0",

    "vue-template-compiler": "^2.6.10",

    "webpack": "^4.29.6",

    "webpack-cli": "^3.2.3",

    "mp-webpack-plugin": "latest"

  },

  "keywords": [],

  "author": "",

  "license": "ISC"

}

安裝依賴包:

npm install

2.2 配置 webpack

 02-mulpages 目錄下創(chuàng)建 build 文件夾,在文件夾下創(chuàng)建 webpack.mp.config.js 文件,內(nèi)容如下:

const path = require('path')

const webpack = require('webpack')

const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const { VueLoaderPlugin } = require('vue-loader')

const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');

const TerserPlugin = require('terser-webpack-plugin')

const MpPlugin = require('mp-webpack-plugin') // 用于構(gòu)建小程序代碼的 webpack 插件

 

const isOptimize = false // 是否壓縮業(yè)務(wù)代碼,開發(fā)者工具可能無(wú)法完美支持業(yè)務(wù)代碼使用到的 es 特性,建議自己做代碼壓縮

 

module.exports = {

  mode: 'production',

  entry: {

    page1: path.resolve(__dirname, '../src/page1/main.mp.js'),

    page2: path.resolve(__dirname, '../src/page2/main.mp.js'),

    page3: path.resolve(__dirname, '../src/page3/main.mp.js'),

  },

  output: {

    path: path.resolve(__dirname, '../dist/mp/common'), // 放到小程序代碼目錄中的 common 目錄下

    filename: '[name].js', // 必需字段,不能修改

    library: 'createApp', // 必需字段,不能修改

    libraryExport: 'default', // 必需字段,不能修改

    libraryTarget: 'window', // 必需字段,不能修改

  },

  target: 'web', // 必需字段,不能修改

  optimization: {

    runtimeChunk: false, // 必需字段,不能修改

    splitChunks: { // 代碼分隔配置,不建議修改

      chunks: 'all',

      minSize: 1000,

      maxSize: 0,

      minChunks: 1,

      maxAsyncRequests: 100,

      maxInitialRequests: 100,

      automaticNameDelimiter: '~',

      name: true,

      cacheGroups: {

        vendors: {

          test: /[\\/]node_modules[\\/]/,

          priority: -10

        },

        default: {

          minChunks: 2,

          priority: -20,

          reuseExistingChunk: true

        }

      }

    },

 

    minimizer: isOptimize ? [

      // 壓縮CSS

      new OptimizeCSSAssetsPlugin({

        assetNameRegExp: /\.(css|wxss)$/g,

        cssProcessor: require('cssnano'),

        cssProcessorPluginOptions: {

          preset: ['default', {

            discardComments: {

              removeAll: true,

            },

            minifySelectors: false, // 因?yàn)?wxss 編譯器不支持 .some>:first-child 這樣格式的代碼,所以暫時(shí)禁掉這個(gè)

          }],

        },

        canPrint: false

      }),

      // 壓縮 js

      new TerserPlugin({

        test: /\.js(\?.*)?$/i,

        parallel: true,

      })

    ] : [],

  },

  module: {

    rules: [

      {

        test: /\.css$/,

        use: [

          MiniCssExtractPlugin.loader,

          'css-loader'

        ],

      },

      {

        test: /\.vue$/,

        loader: [

          'vue-loader',

        ],

      },

      {

        test: /\.js$/,

        use: {

          loader: 'babel-loader',

          options: {

            presets: ['env']

          }

        },

        exclude: /node_modules/

      },

      {

        test: /\.(png|jpg|gif|svg)$/,

        loader: 'file-loader',

        options: {

          name: '[name].[ext]?[hash]'

        }

      }

    ]

  },

 

  resolve: {

    extensions: ['*', '.js', '.vue', '.json']

  },

 

  plugins: [

    new webpack.DefinePlugin({

      'process.env.isMiniprogram': true, // 注入環(huán)境變量,用于業(yè)務(wù)代碼判斷

    }),

    new MiniCssExtractPlugin({

      filename: '[name].wxss',

    }),

    new VueLoaderPlugin(),

    new MpPlugin(require('./miniprogram.config.js')),

  ],

}

 02-mulpages/build 文件夾下創(chuàng)建 miniprogram.config.js 文件,內(nèi)容如下:

module.exports = {    

    origin: 'https://test.miniprogram.com',    

    entry: '/',    

    router: {        

        page1: ['/a'],

        page2: ['/b'],

        page3: ['/c'],

    },    

    redirect: {        

        notFound: 'page1',        

        accessDenied: 'page1',

    },

    generate: {

    appEntry: 'miniprogram-app',

    // 構(gòu)建完成后是否自動(dòng)安裝小程序依賴。'npm':使用 npm 自動(dòng)安裝依賴

        autoBuildNpm: 'npm'

    },

    runtime: {

        cookieStore: 'memory',

    },

    app: {

        navigationBarTitleText: 'kbone-multiple-pages',

    },

    global: {

        share: true,

    },

    pages: {

        page1: {

            extra: {

                navigationBarTitleText: 'page1',

            },

        },

    },

    projectConfig: {

        appid: '',

    projectname: 'kbone-multiple-pages',

    },

    packageConfig: {

        author: 'Felixlu',

    }

}

2.3 編寫三個(gè)頁(yè)面

 /src/ 下創(chuàng)建 page1, page2, page3 三個(gè)文件夾,在文件夾里創(chuàng)建三個(gè)頁(yè)面,每個(gè)頁(yè)面由 App.vue 和 main.mp.js 兩個(gè)文件組成。

1、page1 頁(yè)面

/src/page1/App.vue 內(nèi)容:

<template>

  <div class="cnt">

    <Header></Header>

    <p>當(dāng)前 url:{{url}}</p>

    <a href="/b">當(dāng)前頁(yè)跳轉(zhuǎn)</a>

    <a href="/c" target="_blank">新開頁(yè)面跳轉(zhuǎn)</a>

    <button @click="onClickJump">當(dāng)前頁(yè)跳轉(zhuǎn)</button>

    <button @click="onClickOpen">新開頁(yè)面跳轉(zhuǎn)</button>

    <Footer></Footer>

  </div>

</template>

 

<script>

import Header from '../common/Header.vue'

import Footer from '../common/Footer.vue'

export default {

  name: 'App',

  components: {

    Header,

    Footer

  },

  data() {

    return {

      url: location.href,

    }

  },

  created() {

    window.addEventListener('wxload', query => console.log('page1 wxload', query))

    window.addEventListener('wxshow', () => console.log('page1 wxshow'))

    window.addEventListener('wxready', () => console.log('page1 wxready'))

    window.addEventListener('wxhide', () => console.log('page1 wxhide'))

    window.addEventListener('wxunload', () => console.log('page1 wxunload'))

    window.=> {

      return {

        title: 'kbone-demo',

        // path: '/a', // 當(dāng)前頁(yè)面

        // path: 'https://test.miniprogram.com/a', // 當(dāng)前頁(yè)面的完整 url

        // path: '/b', // 其他頁(yè)面

        // path: 'https://test.miniprogram.com/b', // 其他頁(yè)面的完整 url

        miniprogramPath: `/pages/page2/index?type=share&targeturl=${encodeURIComponent('https://test.miniprogram.com/b')}`, // 自己組裝分享頁(yè)面路由

      }

    }

  },

  mounted() {

    // cookie

    console.log('before set cookie', document.cookie)

    document.cookie = `time=${+new Date()}; expires=Wed Jan 01 2220 00:00:00 GMT+0800; path=/`

    console.log('after set cookie', document.cookie)

  },

  methods: {

    onClickJump() {

      window.location.href = '/b'

    },

    onClickOpen() {

      window.open('/c')

    },

  },

}

</script>

 

<style>

.cnt {

  margin-top: 20px;

}

a, button {

  display: block;

  width: 100%;

  height: 30px;

  line-height: 30px;

  text-align: center;

  font-size: 20px;

  border: 1px solid #ddd;

}

</style>

/src/page1/main.mp.js 內(nèi)容:

import Vue from 'vue'

import App from './App.vue'

 

export default function createApp() {

  const container = document.createElement('div')

  container.id = 'app'

  document.body.appendChild(container)

 

  return new Vue({

    el: '#app',

    render: h => h(App)

  })

}

/src/common/Header.vue 內(nèi)容:

<template>

  <div class="header">

    <p>wechat-miniprogram-header</p>

  </div>

</template>

 

<script>

import add from 'add'

import { printf } from './utils'

export default {

  mounted() {

    printf('I am Header --> ' + add([7, 8]))

  },

}

</script>

 

<style>

.header {

  margin-bottom: 10px;

  width: 100%;

  text-align: center;

}

</style>

/src/common/utils.js 內(nèi)容:

export function printf(str) {

  console.log('common/utils.js --> ', str)

}

/src/common/Footer.vue 內(nèi)容:

<template>

  <div class="footer">

    <p>wechat-miniprogram-footer</p>

  </div>

</template>

 

<script>

export default {}

</script>

 

<style>

.footer {

  margin-top: 10px;

  width: 100%;

  text-align: center;

}

</style>

2、page2 頁(yè)面

/src/page2/App.vue 內(nèi)容:

<template>

  <div class="cnt">

    <Header></Header>

    <p>當(dāng)前 url:{{url}}</p>

    <a href="/a">回到首頁(yè)</a>

    <button @click="onClickJump">回到首頁(yè)</button>

    <button @click="onClickReLaunch">relaunch</button>

    <Footer></Footer>

  </div>

</template>

 

<script>

import Header from '../common/Header.vue'

import Footer from '../common/Footer.vue'

export default {

  name: 'App',

  components: {

    Header,

    Footer

  },

  data() {

    return {

      url: location.href,

    }

  },

  created() {

    window.addEventListener('wxload', query => console.log('page2 wxload', query))

    window.addEventListener('wxshow', () => console.log('page2 wxshow'))

    window.addEventListener('wxready', () => console.log('page2 wxready'))

    window.addEventListener('wxhide', () => console.log('page2 wxhide'))

    window.addEventListener('wxunload', () => console.log('page2 wxunload'))

    window.=> {

      return {

        title: 'kbone-demo',

        path: '/a',

      }

    }

  },

  methods: {

    onClickJump() {

      window.location.href = '/a'

    },

    onClickReLaunch() {

      wx.reLaunch({

        url: `/pages/page1/index?type=jump&targeturl=${encodeURIComponent('/a')}`,

      })

    },

  },

}

</script>

 

<style>

.cnt {

  margin-top: 20px;

}

a, button {

  display: block;

  width: 100%;

  height: 30px;

  line-height: 30px;

  text-align: center;

  font-size: 20px;

  border: 1px solid #ddd;

}

</style>

/src/page2/main.mp.js 內(nèi)容:

import Vue from 'vue'

import App from './App.vue'

 

export default function createApp() {

  const container = document.createElement('div')

  container.id = 'app'

  document.body.appendChild(container)

 

  return new Vue({

    el: '#app',

    render: h => h(App)

  })

}

3、page3 頁(yè)面

/src/page3/App.vue 內(nèi)容:

<template>

  <div class="cnt">

    <Header></Header>

    <p>當(dāng)前 url:{{url}}</p>

    <button @click="onClickBack">回到上一頁(yè)</button>

    <button @click="onClickClose">關(guān)閉當(dāng)前窗口</button>

    <Footer></Footer>

  </div>

</template>

 

<script>

import Header from '../common/Header.vue'

import Footer from '../common/Footer.vue'

export default {

  name: 'App',

  components: {

    Header,

    Footer

  },

  data() {

    return {

      url: location.href,

    }

  },

  created() {

    window.addEventListener('wxload', query => console.log('page3 wxload', query))

    window.addEventListener('wxshow', () => console.log('page3 wxshow'))

    window.addEventListener('wxready', () => console.log('page3 wxready'))

    window.addEventListener('wxhide', () => console.log('page3 wxhide'))

    window.addEventListener('wxunload', () => console.log('page3 wxunload'))

    window.=> {

      return {

        title: 'kbone-demo',

        path: '/a',

      }

    }

  },

  methods: {

    onClickBack() {

      if (process.env.isMiniprogram) {

        wx.navigateBack()

      }

    },

    onClickClose() {

      window.close()

    },

  },

}

</script>

 

<style>

.cnt {

  margin-top: 20px;

}

a, button {

  display: block;

  width: 100%;

  height: 30px;

  line-height: 30px;

  text-align: center;

  font-size: 20px;

  border: 1px solid #ddd;

}

</style>

/src/page3/main.mp.js 內(nèi)容:

import Vue from 'vue'

import App from './App.vue'

 

export default function createApp() {

  const container = document.createElement('div')

  container.id = 'app'

  document.body.appendChild(container)

 

  return new Vue({

    el: '#app',

    render: h => h(App)

  })

}

2.4 小程序端效果預(yù)覽

npm run mp

好程序員web前端培訓(xùn)分享kbone高級(jí)-事件系統(tǒng)

好程序員web前端培訓(xùn)分享kbone高級(jí)-事件系統(tǒng)

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI