我正在使用一个非常简单的 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_key
和 destinationKey
等于 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.sourceKey
和this.destinationKey
,指定您想要 Vue 实例的属性(而不是其他地方定义的变量)。你只能留下this.
在模板中。
对于您的第一个错误,请确保 some_key
和some_other_key
是在 Vue 实例中定义的变量,位于 data() { ... }
下、计算属性等等,如错误消息所示。
关于javascript - 将 props 传递给 vue2 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49078786/