vue-js-bridge for Vue.js
then
或者async/await
等方式yarn:
yarn add vue-webview-js-bridge
npm:
npm i vue-webview-js-bridge
// main.js
import Vue from 'vue'
import VueJsBridge from 'vue-webview-js-bridge'
Vue.use(VueJsBridge, {
debug: true,
nativeHandlerName: 'testObjcCallback',
mock: true,
mockHandler (payload, next) {
// mock by payload
// call next(data) to mock data
}
// ...
})
// component.vue
export default {
name: 'HelloWorld',
props: {
msg: String
},
data () {
return {
code: ''
}
},
mounted () {
this.$bridge.registerHandler('testJavascriptHandler', (data, callback) => {
this.code = data
console.log('data from native:', data)
const responseData = { 'Javascript Says':'Right back atcha!' }
console.log('JS responding with', responseData)
callback(responseData)
})
},
methods: {
async callNative () {
try {
let res = await this.$bridge.callHandler({
type: 'optionType',
data: {
name: 'optionData'
}
})
this.code = res
} catch (error) {
console.log('error', error)
}
}
}
}
// ...
import VueJsBridge, { pluginOption } from 'vue-webview-js-bridge'
interface Payload<T = any> {
type: string
data?: T
}
interface Response<T = any> {
code: number
data?: T
}
const option:pluginOption<Payload, Response> = {
debug: true,
nativeHandlerName: 'testObjcCallback',
mock: false,
mockHandler (payload, next) {
next(Object.assign({ code: 200 }, {
data: 'code from native'
}))
}
}
Vue.use(VueJsBridge, option)
// ...
import { Vue, Component, Prop } from 'vue-property-decorator'
interface Payload<T = any> {
type: string
data?: T
}
interface Response<T = any> {
code: number
data?: T
}
@Component
export default class HelloWorld extends Vue {
@Prop({ default: '' }) private msg!: string
code: string = ''
mounted () {
this.$bridge.registerHandler<string, object>('testJavascriptHandler', (data, callback) => {
this.code = data
console.log('data from native:', data)
const responseData:object = { 'Javascript Says': 'Right back atcha!' }
console.log('JS responding with', responseData)
callback(responseData)
})
}
private async callNative () {
try {
let res = await this.$bridge.callHandler<Payload<object>, Response<string>>({
type: 'optionType',
data: {
name: 'optionData'
}
})
this.code = res.data
} catch (error) {
console.log('error', error)
}
}
}
true
200
ms
native调用前端注册的方法最好也要延时处理,避免前端还未注册时候native调用导致的问题
'nativeHandler'
true
null
mockHandler (payload, next) {
// mock by payload
// switch(payload) {
// case 1:
// next(mockData)
// break
// ...
// }
// call next(data) to mock data
}
this.$bridge.registerHandler('testJavascriptHandler', (data, callback) => {
this.code = data
console.log('data from native:', data)
const responseData = { 'Javascript Says':'Right back atcha!' }
console.log('JS responding with', responseData)
callback(responseData)
})
this.$bridge.callHandler({
type: 'optionType', // 标识调用native的功能
data: { // 传到native的数据
name: 'optionData'
}
})