本篇內(nèi)容介紹了“怎么用kbone實(shí)現(xiàn)跨頁面通信和跨頁面數(shù)據(jù)共享”的有關(guān)知識,在實(shí)際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!
創(chuàng)新互聯(lián)公司是一家專注于成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)、外貿(mào)營銷網(wǎng)站建設(shè)與策劃設(shè)計(jì),班瑪網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)十載,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:班瑪?shù)鹊貐^(qū)。班瑪做網(wǎng)站價(jià)格咨詢:18982081108
// 頁面1
window.$$subscribe('hello', data => {
console.log('receive a msg: ', data)
})
// 頁面2
window.$$publish('hello',
'I am june')
在訂閱了此消息的頁面則會輸出 receive a msg: I am june。
PS:如果需要取消訂閱消息,可以使用 window.$$unsubscribe 接口進(jìn)行取消。
PS:頁面關(guān)閉后,會取消該頁面所有的訂閱。
如果需要跨頁面數(shù)據(jù)進(jìn)行共享,可以使用 window.$$global 對象,所有頁面的 window.$$global 均會指向同一個(gè)對象:
// 頁面1
window.$$global.name =
'june'
// 頁面2
console.log(window.$$global.name)
// 輸出 june
PS:具體 API 可參考 dom/bom 擴(kuò)展 API 文檔。
在 kbone-advanced 目錄下創(chuàng)建 08-share-message 目錄,本案例在這個(gè)目錄下完成。
cd 08-share-message
npm init -y
編輯 package.json:
{
"scripts": {
"mp":
"cross-env NODE_ENV=production webpack --config build/webpack.mp.config.js --progress --hide-modules"
},
"dependencies": {
"vue":
"^2.5.11",
"vuex":
"^3.1.3"
},
"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",
"babel-preset-stage-3":
"^6.24.1",
"cross-env":
"^5.0.5",
"css-loader":
"^0.28.7",
"extract-text-webpack-plugin":
"^3.0.2",
"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"
}
}
安裝依賴包:
npm install
在 08-share-message/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ā)者工具可能無法完美支持業(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'),
page4: path.resolve(__dirname, '../src/page4/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', 'stage-3'],
},
}],
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': process.env.isMiniprogram, // 注入環(huán)境變量,用于業(yè)務(wù)代碼判斷
}),
new MiniCssExtractPlugin({
filename: '[name].wxss',
}),
new VueLoaderPlugin(),
new MpPlugin(require('./miniprogram.config.js')),
],
}
在 08-share-message/build 目錄下創(chuàng)建 miniprogram.config.js,內(nèi)容如下:
module.exports = {
origin: 'https://test.miniprogram.com',
entry: '/',
router: {
page1: ['/'],
page2: ['/page2'],
page3: ['/page3'],
page4: ['/page4'],
},
redirect: {
notFound: 'page1',
accessDenied: 'page1',
},
generate: {
// 構(gòu)建完成后是否自動安裝小程序依賴。'npm':使用 npm 自動安裝依賴
autoBuildNpm: 'npm'
},
app: {
navigationBarTitleText: 'miniprogram-project',
},
projectConfig: {
appid: '',
projectname: 'kbone-demo22',
},
packageConfig: {
author: 'wechat-miniprogram',
},
}
在 /src/ 下創(chuàng)建 page1 文件夾,在 page1 下創(chuàng)建 main.mp.js 文件,內(nèi)容如下:
import Vue
from 'vue'
import {createStore}
from '../store'
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',
store: createStore(),
render:
h => h(App)
})
}
在 /src/ 下創(chuàng)建 store 文件夾,在 store 下創(chuàng)建 index.js 文件,內(nèi)容如下:
import Vue
from 'vue'
import Vuex
from 'vuex'
Vue.use(Vuex)
export function createStore() {
const state =
window.$$global.state || {
count:
0,
data: {},
}
window.$$global.state = state
return new Vuex.Store({
state,
actions: {
FETCH_DATA:
({commit}, data) => {
setTimeout(() => {
commit('SET_DATA', data)
},
100)
},
},
mutations: {
SET_DATA:
(state, data) => {
state.count++
Vue.set(state.data,
'name', data.name)
},
},
});
}
在 /src/page1 下創(chuàng)建 App.vue 文件,內(nèi)容如下:
<template>
<div class="cnt">
<Header></Header>
<a href="/page2" target="_blank">跳轉(zhuǎn)頁面2</a>
<a href="/page3" target="_blank">跳轉(zhuǎn)頁面3</a>
<a href="/page4" target="_blank">跳轉(zhuǎn)頁面4</a>
<button @click="startFetchData">開啟數(shù)據(jù)更新</button>
<div>count: {{count}} - name: {{data.name || ''}}</div>
<Footer></Footer>
</div>
</template>
<script>
import {mapState, mapActions}
from 'vuex'
import Header
from '../common/Header.vue'
import Footer
from '../common/Footer.vue'
export default {
name:
'App',
components: {
Header,
Footer
},
computed: {
...mapState(['count',
'data'])
},
mounted() {
let count =
0
setInterval(() => {
console.log('開始發(fā)送輪詢消息,10s一次')
window.$$publish('polling', ++count)
},
10000)
window.$$subscribe('page1', data =>
console.log('首頁收到來自其他頁面的消息', data))
},
methods: {
startFetchData() {
const nameList = ['june',
'green']
let count =
0
let name = nameList[count %
2]
setInterval(() => {
count++
name = nameList[count %
2]
this.FETCH_DATA({
count,
name,
})
},
1000)
},
...mapActions(['FETCH_DATA'])
},
}
</script>
<style>
.cnt {
margin-top:
20px;
text-align: center;
}
a,
button {
display: block;
width:
100%;
height:
30px;
line-height:
30px;
text-align: center;
font-size:
20px;
border:
1px solid
#ddd;
}
</style>
在 /src/ 下創(chuàng)建 common 文件夾,在 common 下創(chuàng)建 Header.vue 文件,內(nèi)容如下:
<template>
<div class="header">
<p>wechat-miniprogram-header</p>
</div>
</template>
<script>
export default {}
</script>
<style>
.header {
margin-bottom:
10px;
width:
100%;
text-align: center;
}
</style>
在 /src/common 下創(chuàng)建 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>
在 /src/ 下創(chuàng)建 page2 文件夾,在 page2 下創(chuàng)建 main.mp.js 文件,內(nèi)容如下:
import Vue
from 'vue'
import {createStore}
from '../store'
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',
store: createStore(),
render:
h => h(App)
})
}
在 /src/page2 下創(chuàng)建 App.js 文件,內(nèi)容如下:
<template>
<div class="cnt">
<Header></Header>
<a href="/page3" target="_blank">跳轉(zhuǎn)頁面3</a>
<a href="/page4" target="_blank">跳轉(zhuǎn)頁面4</a>
<button @click="onClickBack">回到上一頁</button>
<button @click="sendPage1">發(fā)布消息給首頁</button>
<div>count: {{count}} - name: {{data.name || ''}}</div>
<Footer></Footer>
</div>
</template>
<script>
import {mapState}
from 'vuex'
import Header
from '../common/Header.vue'
import Footer
from '../common/Footer.vue'
export default {
name:
'App',
components: {
Header,
Footer
},
computed: {
...mapState(['count',
'data'])
},
mounted() {
window.$$subscribe('polling', count =>
console.log('頁面2收到來自首頁的輪詢消息 --> ' + count))
window.$$subscribe('page2', data =>
console.log('頁面2收到來自頁面3的消息', data))
window.$$subscribe('page23', data =>
console.log('頁面2收到來自頁面4的消息', data))
},
methods: {
onClickBack() {
if (process.env.isMiniprogram) {
wx.navigateBack()
}
},
sendPage1() {
window.$$publish('page1', {from:
'頁面2',
to:
'首頁'})
},
},
}
</script>
<style>
.cnt {
margin-top:
20px;
text-align: center;
}
a,
button {
display: block;
width:
100%;
height:
30px;
line-height:
30px;
text-align: center;
font-size:
20px;
border:
1px solid
#ddd;
}
</style>
在 /src/ 下創(chuàng)建 page3 文件夾,在 page3 下創(chuàng)建 main.mp.js 文件,內(nèi)容如下:
import Vue
from 'vue'
import {createStore}
from '../store'
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',
store: createStore(),
render:
h => h(App)
})
}
在 /src/page3 下創(chuàng)建 App.js 文件,內(nèi)容如下:
<template>
<div class="cnt">
<Header></Header>
<a href="/page4" target="_blank">跳轉(zhuǎn)頁面4</a>
<button @click="onClickBack">回到上一頁</button>
<button @click="sendPage1">發(fā)布消息給首頁</button>
<button @click="sendPage2">發(fā)布消息給頁面2</button>
<div>count: {{count}} - name: {{data.name || ''}}</div>
<Footer></Footer>
</div>
</template>
<script>
import {mapState}
from 'vuex'
import Header
from '../common/Header.vue'
import Footer
from '../common/Footer.vue'
export default {
name:
'App',
components: {
Header,
Footer
},
computed: {
...mapState(['count',
'data'])
},
mounted() {
window.$$subscribe('polling', count =>
console.log('頁面3收到來自首頁的輪詢消息 --> ' + count))
window.$$subscribe('page23', data =>
console.log('頁面3收到來自頁面4的消息', data))
},
methods: {
onClickBack() {
if (process.env.isMiniprogram) {
wx.navigateBack()
}
},
sendPage1() {
window.$$publish('page1', {from:
'頁面3',
to:
'首頁'})
},
sendPage2() {
window.$$publish('page2', {from:
'頁面3',
to:
'頁面2'})
},
},
}
</script>
<style>
.cnt {
margin-top:
20px;
text-align: center;
}
a,
button {
display: block;
width:
100%;
height:
30px;
line-height:
30px;
text-align: center;
font-size:
20px;
border:
1px solid
#ddd;
}
</style>
在 /src/ 下創(chuàng)建 page4 文件夾,在 page4 下創(chuàng)建 main.mp.js 文件,內(nèi)容如下:
import Vue
from 'vue'
import {createStore}
from '../store'
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',
store: createStore(),
render:
h => h(App)
})
}
在 /src/page4 下創(chuàng)建 App.js 文件,內(nèi)容如下:
<template>
<div class="cnt">
<Header></Header>
<button @click="onClickBack">回到上一頁</button>
<button @click="sendPage1">發(fā)布消息給首頁</button>
<button @click="sendPage23">發(fā)布消息給頁面2和頁面3</button>
<div>count: {{count}} - name: {{data.name || ''}}</div>
<Footer></Footer>
</div>
</template>
<script>
import {mapState}
from 'vuex'
import Header
from '../common/Header.vue'
import Footer
from '../common/Footer.vue'
export default {
name:
'App',
components: {
Header,
Footer
},
computed: {
...mapState(['count',
'data'])
},
mounted() {
window.$$subscribe('polling', count =>
console.log('頁面4收到來自首頁的輪詢消息 --> ' + count))
},
methods: {
onClickBack() {
if (process.env.isMiniprogram) {
wx.navigateBack()
}
},
sendPage1() {
window.$$publish('page1', {from:
'頁面4',
to:
'首頁'})
},
sendPage23() {
window.$$publish('page23', {from:
'頁面4',
to:
'頁面2、頁面3'})
},
},
}
</script>
<style>
.cnt {
margin-top:
20px;
text-align: center;
}
a,
button {
display: block;
width:
100%;
height:
30px;
line-height:
30px;
text-align: center;
font-size:
20px;
border:
1px solid
#ddd;
}
</style>
npm run mp
“怎么用kbone實(shí)現(xiàn)跨頁面通信和跨頁面數(shù)據(jù)共享”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!
網(wǎng)站欄目:怎么用kbone實(shí)現(xiàn)跨頁面通信和跨頁面數(shù)據(jù)共享
本文地址:http://aaarwkj.com/article4/ihphoe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)、自適應(yīng)網(wǎng)站、網(wǎng)站營銷、定制網(wǎng)站、服務(wù)器托管、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)