如何使用Vuejs点击此组件外部的按钮来获取组件的内容?

时间:2018-04-02 17:11:57

标签: laravel vue.js vuejs2 vue-component

我有一个模态,我想在每次单击按钮时更新内容。此按钮不在组件中,我需要它来更新项目slug,它将用于从API获取内容。

我是Vuejs的新手。

这是我的app.js:

Vue.component('pop-modal', require('./components/PopModal.vue'));

const app = new Vue({
    el: '#app',
    data: {
        popSlug: 0
    },
    methods: {
        updatePop: function(popSlug) {
            this.popSlug = popSlug
            console.log(this.popSlug)
        }
    }
});

这是我的组成部分:

<template>
    <div class="modal fade" id="popModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <h1>{{ pop.name }}</h1>
                <p>test: {{ this.$parent.popSlug }}</p>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                pop: {},
            }
        },
        watch: {
            popSlug(newPopslug) {
                this.popSlug = newPopslug
                this.fetchData()
                console.log('new popslug value!')
            }
        },
        mounted() {
            console.log('Component pop-modal mounted.')
        },
        methods: {
            fetchData() {
                axios.get(route('api.pops.show'), this.popSlug)
                .then(response => {
                  // JSON responses are automatically parsed.
                  this.pop = response.data
                })
                .catch(e => {
                  this.errors.push(e)
                })
                console.log('fetchData')
            }
        }
    }
</script>

我知道我做错了但我不知道该怎么做。 从不触发watch方法,因为popSlug不是数据属性。 我可以通过以下方式获得popSlug值:

{{ this.$parent.popSlug }}

但我认为这是错误的做法。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您可以将import UIKit class LoginViewController: UIViewController { @IBAction func btnActionLogin(_ sender: Any?) { print("Why is this error?") } } 值作为道具传递给组件,如文档here中所述。然后在popSlug组件中,您可以将值视为pop-modal,并且手表会对更改做出反应。只要确保不修改组件内的prop值,因为它应该是一个只读值。

这是一个有效的examplethis.popSlug仅用于显示正在调用手表。您可以直接在模板中使用internalValue