我需要将变量传递给组件。我的设置是这样的:
主要: Meet.vue
<html>
<div class="carousel-cell">
<Category :searchTerm="woman"></Category>
</div>
<div class="carousel-cell">
<Category :searchTerm="men"></Category>
</div>
[..]
<script>
import Category from './Category'
export default {
components: {
Category
},
子: Category.vue :
export default {
data () {
return {
search: [how to access the **searchTerm** here?]
如何从Category.vue中的Meet.vue访问 searchTerm <Category :searchTerm="woman"></Category>
?
答案 0 :(得分:2)
您必须按照VueJS Documentation
的说明在类别组件中引入此searchTerm
属性
在Category.vue
export default {
props: ['searchTerm'],
// Your component code (computed, methods, watch, ...)
}
如果您想对道具进行验证
export default {
props: {
searchTerm: {
type: String,
required: false,
// If not required, it's possible to give a default value
default: "woman"
},
}
// Your component code (computed, methods, watch, ...)
}
然后您可以使用this.searchTerm
阅读道具。
例如,您也可以直接在<template></template>
内以{{ searchTerm }}
阅读它。
如果在某个时候需要编写一个道具,那么最好将其值复制到局部变量中并使用它
props: ['searchTerm'],
data: function () {
return {
// Write on search variable if needed
search: this.searchTerm
}
}
答案 1 :(得分:1)
答案 2 :(得分:1)
在调用Category
组件时执行以下操作。
<Category :search="woman"></Category>
此处:search:"woman"
表示将woman
作为值传递给Category
组件的属性。
然后在Category
组件中:
export default {
props: {
search: {type: string, required: true}
//Here it will give error if the search is passed anything but string
//And if search is not passed it will give error.
}
//Everything else
或
export default {
props: [search], //No checking of data type and it's not requried
//Everything else