javascript - 将 props 传递给 vue2 组件

标签 javascript vue.js vuejs2

我正在使用一个非常简单的 vue 组件,我想通过 props 将信息传递给它。在 HTML 中,它看起来像:

<myapp v-bind:source-key="some_key" v-bind:destination-key="some_other_key"></myapp>

该组件如下所示:

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card card-default">
                    <div class="card-header">Example Component</div>

                    <div class="card-body">
                        I'm an example component.
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        props: ['sourceKey', 'destinationKey'],
        mounted() {
            this.$http.get('/map/' + sourceKey + '/' + destinationKey)
                .then(function (response) {
                    console.dir(response)
                })
                .catch(function (error) {
                    console.dir(error);
                });
            console.log('got here')
        }
    }
</script>

我希望这会将 Prop sourceKey 设置为等于 some_keydestinationKey 等于 some_other_key组件,但我收到错误:

[Vue warn]: Property or method "some_key" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

看来预期值被视为关键?然后还有更多错误表明 sourceKey 变量从未定义:

[Vue warn]: Error in mounted hook: "ReferenceError: sourceKey is not defined"

如果不在 props block 中,我应该在哪里定义 props?

最佳答案

这里:this.$http.get('/map/' + sourceKey + '/' + destinationKey)

<script> ,您需要访问this.sourceKeythis.destinationKey ,指定您想要 Vue 实例的属性(而不是其他地方定义的变量)。你只能留下this.在模板中。

对于您的第一个错误,请确保 some_keysome_other_key是在 Vue 实例中定义的变量,位于 data() { ... } 下、计算属性等等,如错误消息所示。

关于javascript - 将 props 传递给 vue2 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49078786/

相关文章:

javascript - 当我最大化窗口或返回窗口模式时,$(window).resize() 事件在 Chrome 中不起作用

javascript - Vue.js 消费 json

javascript - 将数据从 onSnapshot firestore 分配给 Vue ref 变量时出现问题

javascript - Laravel 和 vue.js 值数组

javascript - 在已安装的情况下仅在 vue 中重新加载页面一次

javascript - 运行 share/scripts/javascript 命令行宏

javascript - 识别第三方 cookie

javascript - 如何使用 Angular 正确开发它?

javascript - 使用 Vue.js 为恒定(未知)数据流设置动画的最佳方式?

node.js - Vue 无法使用 axios hook 打开 .json 文件