vue.js - 如何在全局 vue 组件中调用方法?

标签 vue.js vuejs2 global vue-component vuex

我有根 vue 组件 app.js:

...
const app = new Vue({
    el: '#app',
    ...
    methods: {
        modalShow: function(target, id=null, message=null){
           ...
        },
        ...
    }
});

我有一个这样的子组件:

<template>
    <div>
        <ul>
            <li> 
                <a href="#" class="thumbnail"
                   title="Add photo" 
                   @click="modalShow('modal-add-photo', product.id)"
                > 
                    <span class="fa fa-plus fa-2x"></span> 
                </a> 
            </li>
        </ul>
    </div>
</template>

<script>

    export default {
        ...
        methods: {
            ...
        }
    }
</script>

modalShow 方法在根目录中。怎么才能从子调用呢?

如果现在执行上面的代码,我会得到以下错误:

[Vue warn]: Property or method "modalShow" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

最佳答案

modalShow 方法向下传递给子组件。

<child :modal-show="modalShow"></child>

export default {
  props:["modalShow"]
}

然后就可以在child中使用这个方法了。

关于vue.js - 如何在全局 vue 组件中调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45094010/

相关文章:

javascript - 导出 2 webpack 配置常量

jquery - v-model 不会检测 jQuery 触发事件所做的更改

npm - Vuejs : npm run dev not working

php - Laravel Echo 500 错误(广播/授权)?

javascript - Vue.js 3.0 : Read and set object properties from method

javascript - 如果 switch 在 VueJS/Vuetify JS 中切换,则调用函数

firebase - 为什么我无法在 firebase 'this ' 回调中访问 vuejs 'then'?

python - 在 Python 中,什么是全局语句?

object - 主干和 Requirejs。如何从任何地方访问我的 Backbone 路由器

php - 在 PHP 类中使用全局 DB 变量