畫重點:本本介紹webView和vue交互包含一下4點
1、設置title
2、app url傳參到vue
3、js調用app本地方法
4、app調用js方法
一 設置title,由於vue是單頁應用,傳統項目那樣配置<title>標題</title>會無效
1、vue設置
1)在components下面創建多個vue組件,如下圖所示:
2)配置路由;在router/index.js文件中配置
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import FirstPage from '@/components/FirstPage' import TwoPage from '@/components/TwoPage' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld, meta:{ title:"首頁" } }, { path: '/firstPage', name: 'FirstPage', component: FirstPage, meta:{ title:"firstPage" } }, { path: '/twoPage', name: 'TwoPage', component: TwoPage, meta:{ title:"twoPage" } } ] })
3)在main.js中設置
router.afterEach(function (to, from) { if(to.meta.title){ document.title = to.meta.title; } });
4)運行項目自測 npm run dev,瀏覽器訪問:http://localhost:8080;跳轉頁面如發現title有改變說明vue配置title已成功;
2、app webView設置,
1)webView設置WebChromeClient
webView.setWebChromeClient(chromeClient)
2)重寫WebChromeClient的onReceivedTitle(WebView view, String title)方法,其中title就是當前web頁面的title,可將此title設置到app的title中顯示;
二 app url傳參到vue
app提供參數以供前端載入頁面立刻使用,一般采用url傳參
1、vue設置
1)創建utils.js文件,其內容如下(獲取url路徑上的參數)
export default{ getUrlKey: function (name) { return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null } }
2)在main.js中引入utils.js文件,並獲取url上相關的參數;代碼如下
import utils from './utils' let chainName = utils.getUrlKey('chainName') console.log("chainName:"+chainName) alert("chainName:"+chainName)
3)代碼完成后部署項目,瀏覽器訪問 http://localhost:8080?chainName=emememememem;得到下圖所示,證明vue已經接收到參數
三 js調用app本地方法
1、app端設置
1) webview設置 如下:
webView.addJavascriptInterface(this, "app");
@android.webkit.JavascriptInterface
public void actionFromJs(String args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
ToastUtil.toastShort("form web args:" + args);
}
});
}
其中:app 是注入到js中的對象,js中通過app調用actionFromJs方法
2、vue設置
<template>
<div class="hello">
<h1>first page</h1>
<p>傳入原生參數是:js調用了android中的actionFromJs方法</p>
<p><button @click = "callApp()">callApp</button></p>
</div>
</template>
export default{
methods:{
callApp(){
// 由於對象映射,所以調用app對象等於調用Android映射的對象
app.actionFromJs("js調用了app中的actionFromJs方法");
}
}
}
</script>
四 app調用js方法
1、vue設置;vue讓app能調入js方法,需要將方法賦給window;因為vue將js進行封裝操作
<script > export default { mounted() { window.formToApp = this.formToApp; }, methods: { formToApp(args) { alert("app args:" + args); } } } </script>
2、app設置
在需要調用js方法位置執行即可
callJs("formToApp", "app調用了formToApp方法");
public void callJs(String name, String args) { String url = "javascript:" + name + "('" + args + "')"; webView.loadUrl(url); }