You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

52 lines
2.0 KiB

  1. /**
  2. * 递归使用 call 方式this指向
  3. * @param componentName // 需要找的组件的名称
  4. * @param eventName // 事件名称
  5. * @param params // 需要传递的参数
  6. */
  7. function broadcast(componentName, eventName, params) {
  8. // 循环子节点找到名称一样的子节点 否则 递归 当前子节点
  9. this.$children.map(child=>{
  10. if (componentName===child.$options.name) {
  11. child.$emit.apply(child,[eventName].concat(params))
  12. }else {
  13. broadcast.apply(child,[componentName,eventName].concat(params))
  14. }
  15. })
  16. }
  17. export default {
  18. methods: {
  19. /**
  20. * 派发 (向上查找) (一个)
  21. * @param componentName // 需要找的组件的名称
  22. * @param eventName // 事件名称
  23. * @param params // 需要传递的参数
  24. */
  25. dispatch(componentName, eventName, params) {
  26. let parent = this.$parent || this.$root;//$parent 找到最近的父节点 $root 根节点
  27. let name = parent.$options.name; // 获取当前组件实例的name
  28. // 如果当前有节点 && 当前没名称 且 当前名称等于需要传进来的名称的时候就去查找当前的节点
  29. // 循环出当前名称的一样的组件实例
  30. while (parent && (!name||name!==componentName)) {
  31. parent = parent.$parent;
  32. if (parent) {
  33. name = parent.$options.name;
  34. }
  35. }
  36. // 有节点表示当前找到了name一样的实例
  37. if (parent) {
  38. parent.$emit.apply(parent,[eventName].concat(params))
  39. }
  40. },
  41. /**
  42. * 广播 (向下查找) (广播多个)
  43. * @param componentName // 需要找的组件的名称
  44. * @param eventName // 事件名称
  45. * @param params // 需要传递的参数
  46. */
  47. broadcast(componentName, eventName, params) {
  48. broadcast.call(this,componentName, eventName, params)
  49. }
  50. }
  51. }