【问题标题】:Call method other component in vuevue中调用其他组件的方法
【发布时间】:2017-11-21 19:37:55
【问题描述】:

如何在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 进行搜索时,如果

关键字 == ''

调用PostHome组件中的fetchPost方法

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

  • 谢谢。我正在使用 bus.$emit 和 bus.$on。它和我一起工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 2018-09-27
  • 1970-01-01
  • 2019-09-16
  • 2017-12-19
  • 2019-11-11
相关资源
最近更新 更多