【问题标题】:How to fetch content for a component on click of a button outside this component with Vuejs?如何使用 Vuejs 单击该组件外部的按钮来获取组件的内容?
【发布时间】:2018-09-11 22:10:00
【问题描述】:

我有一个模态框,我希望在单击按钮时更新内容。这个按钮不在组件中,我需要它来更新一个 item 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 }}

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

提前感谢您的帮助。

【问题讨论】:

    标签: laravel vue.js vuejs2 vue-component


    【解决方案1】:

    您可以将popSlug 值作为道具传递给组件,如文档here 中所述。然后在pop-modal 组件中,您可以访问this.popSlug 的值,手表将对更改做出反应。只要确保不要修改组件内部的 prop 值,因为它应该是只读值。

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

    【讨论】:

    • 谢谢,但它似乎不起作用,我在组件中添加了 prop,但从未触发 watch。
    • 我添加了一个小提琴示例。希望对您有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2021-10-05
    • 2020-04-19
    • 2017-03-21
    • 2023-04-04
    • 2018-12-04
    • 2021-06-10
    • 2020-06-06
    相关资源
    最近更新 更多