Vue.js - 如何从另一个组件调用方法

新手上路,请多包涵

我正在使用 Vue.Js v2。提交后我想在component2->c2method中调用component1->c1method来重新加载数据。

 Vue.component('component1', {
  methods: {
    c1method: function(){
     alert('this is c1method')
    },
  }
})
Vue.component('component2', {
  methods: {
    c2method: function(){
     component('component1').c1method()//like this
    },
  }
})

原文由 Miri 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 604
2 个回答

对于非父子关系,则与此相同。从任何其他组件调用一个方法,显然是组件的任何方法。只需将 $on 函数添加到 $root 实例并调用任何其他组件访问 $root 并调用 $emit 函数

在第一个组件上

    ……
    挂载(){
        this.$root.$on('component1', () => {
            // 你的代码在这里
            this.c1method()
        }
    }

并在第二个组件中调用 $emit 函数在 $root

    ...
    c2方法:函数(){
     this.$root.$emit('component1') //像这样
    },

它更像是一个套接字。参考这里

https://stackoverflow.com/a/50343039/6090215

原文由 Mir Ayman Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

// Component A
Vue.component('A', {
    created() {
        this.$root.$refs.A = this;
    },
    methods: {
        foo: function() {
            alert('this is A.foo');
        }
    }
});

// Component B
Vue.component('B', {
    methods: {
        bar: function() {
            this.$root.$refs.A.foo();
        }
    }
});

原文由 Sajjad Shirazy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题