中其实就有介绍组件通信, 我这里写下我自己的理解
1: 定义一个方法:
可以在任何组件中定义方法:
this.$on(type, handler)
2: 其他的 ViewModel 中获取这个方法, (此 ViewModel 中必须引用该组件)
xxx.$emit(type, detail); //调用某某组件中的方法(type)
1: xxx , 指的是定义方法的组件,
2: detail, 是需要传入的值
- 格式:
- 字符串(比如图片路径);
- 对象或者数组(传数字), 接受时需要JSON转换
this.eventDetail = JSON.stringify(event.detail)
xxx获取组件的方式
- 子级ViewModel 获取父级组件 使用
this._parent
<element name="foo"> <template> <div> <image src="{{imageUrl}}" class="thumb" onclick="test"></image> <text>{{title}}</text> </div> </template> <style> .thumb { width: 200; height: 200; } </style> <script> module.exports = { data: { title: '', imageUrl: '' }, methods: { test: function () { // Emit notify to parent this._parent.$emit('notify', {a: 1}) } } } </script>
- 父级往子集传值
父级中引用了子集, 需要子组件的id
this.$vm(id).$emit(type, detail)
id为子集的id 类似获取节点