【问题标题】:Pass variable down to VueJS component将变量传递给 VueJS 组件
【发布时间】:2019-09-15 21:32:04
【问题描述】:

我需要将一个变量传递给一个组件。我的设置是这样的:

主要: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 &lt;Category :searchTerm="woman"&gt;&lt;/Category&gt;

【问题讨论】:

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

您必须按照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 阅读您的道具。 你也可以直接在&lt;template&gt;&lt;/template&gt;里面读,比如{{ searchTerm }}


如果在某些时候你需要在你的一个道具上写,最好将它的值复制到一个局部变量上并使用它

props: ['searchTerm'],
data: function () {
  return {
    // Write on search variable if needed
    search: this.searchTerm
  }
}

【讨论】:

  • 感谢您提供此示例。 meet.vue 中更改后有没有办法通过 searchTerm ?我尝试了 v-bind 没有成功:&lt;div class="carousel-cell"&gt; &lt;Category v-bind="search" :searchTerm="search"&gt;&lt;/Category&gt; 搜索词从 meet.vue 中的搜索框中更新:&lt;v-text-field v-model="search" label="Search it..." &gt;&lt;/v-text-field&gt;
    `
  • @Tom 我建议您在 Category 组件中查看您的道具。你可以在这里有一个例子stackoverflow.com/questions/44584292/… - 你可以查看文档以了解它是如何工作的:vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property
  • 【解决方案2】:

    在调用Category 组件时执行以下操作。

    &lt;Category :search="woman"&gt;&lt;/Category&gt;

    这里的: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
    

    【讨论】:

      【解决方案3】:

      你使用的是props,所以答案是:

      export default{
          props: ['searchTerm'],
      

      然后就可以直接使用了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-20
        • 2017-08-13
        • 2017-07-20
        • 2020-05-22
        • 1970-01-01
        • 2017-11-09
        相关资源
        最近更新 更多