在vue中调用方法其他组件

时间:2017-06-19 14:19:48

标签: laravel-5 vue.js components vuejs2 vue-component

如何在Vue中调用方法其他组件?

我有 HeaderSearch

组件
<template>
    <form action="">
        <div class="form-group">
            <div class="input-group">
                <span class="input-group-btn">
                    <button class="btn" type="button">
                        <i class="fa fa-search"></i>
                    </button>
                </span>
                <input type="text" @keyup="search(keyword)" v-model="keyword" class="form-control" placeholder="Search...">
            </div>
        </div>
    </form>
</template>
<script>
export default {
    data(){
        return { keyword: "" };
    },
    methods: {
        search: function(keyword){
                if(keyword == ''){
                    // Want call method fetchPost in PostHome component here
                }else{

                }
        }
    }
}
</script>

我有 PostHome

组件
<template>
        <div>
            <div class="box r_8 box_shadow" v-for="post in posts">
                <div class="box_header">
                    <a :href="post.url">
                        <h3 class="mg_bottom_10" v-text="post.title"></h3>
                    </a>
                    <small v-text="post.description"></small>
                    <a :href="post.url" class="box_header_readmore">Read more</a>
                </div>
                <div class="box_body">
                    <a :href="post.url" v-show="post.thumbnail">
                        <img :src="post.thumbnail" class="img_responsive" style="min-height: 300px;background-color: #f1f1f1;
                        ">
                    </a>
                </div>
                <div class="box_footer" v-show="post.tags.length > 0">
                    <ul>
                        <li v-for="tag in post.tags">
                                <a v-text="tag.name" href="javascript:void(0)"></a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
</template>
<script>
export default {
    data(){
        return {
            posts: null,
        }
    },
    methods: {
        fetchPosts: function(){
            var url = base_url + '/user/posts'
            this.$http.get(url).then(res => {
                this.posts = res.data;
            });
        }
    },
    created: function(){
        this.fetchPosts();
    }
}
</script>

我希望当用户键入keyup时搜索

  

keyword ==&#39;&#39;

PostHome组件中的调用方法 fetchPost 方法

1 个答案:

答案 0 :(得分:0)

如果该方法可重复使用,您可以使用Mixins。

参考:https://vuejs.org/v2/guide/mixins.html