vue:app传递数据给vue组件

这是app打开网页,从app传递数据给vue的子组件里面的methods方法
关键点是需要把vue子组件的methods方法挂载到window上

网址:
https://blog.csdn.net/baidu_33546245/article/details/79304682

Android原生与Vue.js的互相调用
最近研究了一下HybridApp的相关实现技术.主要是Vue与Android原生的交互,
看了一些网上这方面的案例,大部分都是寥寥几笔,有很多地方非常不完善,无法实现我们希望实现的功能,
因此做了许多关于Vue和Android native交互的调研,Demo代码在文章末尾.
总结了几个我碰到的坑:

1,Android如何将自己的消息发送至Vue的每个子Component
2,Android如何传递String类型到Js
3,Js如何加载Android native的图片和其它资源

-----------------------分割线-------------------------

1,Android如何将自己的消息发送至Vue的每个子Component
因为Android无法直接调用每个Vue对象的methods里的方法,只能调用window下面的function,所以我们需要一个模型:
先将消息发至window下的function,通过window下的function调用父组件的代码,再由父组件调用子组件的代码.

Vue代码:使用Vue cli直接创建一个project,
然后在config/index.js中将host由localhost改为电脑的本地Ip,以方便使用在手机端去调试.
关于Vue父组件与子组件的通讯,不得不说Vue的中文文档十分强大,我这种之前从未接触过Vue的Vue萌新,
竟然毫不费力就找了了组件间通讯的详细文档.

1,建立一个ChildComponent.vue的子组件,在其中定义receiveMsgFromParent(msg)函数,代码如下

<template>
<div id="childComponent" style="background-color: #42b983">
<div>{{childMsg}}</div>
<br/>
<button @click="toSecondComponent">去第二个界面</button>
</div>
</template>

<script>
export default {
name: 'childComponent',
data: function () {
return {
childMsg: "This is child component"
}
},
methods: {
receiveMsgFromParent: function (msg) {
alert("" + msg);
this.childMsg = "receive msg = " + msg;
},
toSecondComponent: function () {
this.$router.replace({path: "/SecondComponent"});
}
},
created() {
this.$parent.setComponent(this);
}
}
</script>

2,在App.vue定义一个window下的function,用来让Android的WebView找到该方法,
同时在 App.vue里定义一个setComponent(component)方法,代码如下:

var curComponent;
export default {
name: 'App',
components: {
ChildComponent
},
data: function () {
return {
richtext: "App.vue receive msg"
}
},
methods: {
setComponent: function (component) {
curComponent = component;
}
},
created() {
this.$router.push({path: "ChildComponent"});
},
}

window["receiveMsgFromNative"] = function (msg) {
curComponent.receiveMsgFromParent(msg);
}

3,这个Window下的function如何于路由最上层的Component建立联系,每个ChildComponent在created()时都去调用App.vue的 this.$parent.setComponent(this);方法,
这样就能正确的收到消息传递给路由最上层的vue组件了.

Android部分:
Android这块,我是使用QQ x5浏览器去加载的(据说崩溃率比较低),同时也测试了原生的WebView..

就不详细介绍流程了,网上有很多相关资料.

唯一值得注意的是如果要传递Stirng类型的数据给Js的话,需要在数据前面加上引号...

猜你喜欢

转载自www.cnblogs.com/llqwm/p/9145234.html
今日推荐