将属性添加到vue组件

时间:2018-04-20 14:43:21

标签: javascript vue.js vue-component

我试图创建一个"下拉列表"零件。该组件应该包含标题和路线。我在父设备中为此组件设置javascript时遇到问题。这是我正在使用的。

PARENT COMPONENT:

<template>
  <UserDropdownList v-for="item in items"></UserDropdownList>
</template>


<script>
  import SignUp from "../forms/SignUp";
  import SignIn from "../forms/SignIn";
  import UserDropdownList from "./UserDropdownList";
  import { mixin as clickaway } from 'vue-clickaway';
  export default {
    mixins: [ clickaway ],
    components: {
      SignUp,
      SignIn,
      UserDropdownList
    },
    data: function () {
      return {
        items: [
          { title: 'Profile', route: "/profile" },
          { title: 'Users', route: "/users" }
        ]
      }
    },
    computed: {
      isLoggedIn () {
        return this.$store.getters.isLoggedIn
      },
      userName () {
        return this.$store.getters.currentUser.userName
      },
      isDropdownOpen () {
        return this.$store.getters.dropdownIsOpen
      }
    },
    methods: {
      signOut: function(event) {
        this.$store.commit("CLOSE_DROPDOWN");
        this.$store.commit("LOGOUT");
        this.$router.push('/');
      },
      openDropdown: function() {
        if (event.target.id != "button") {
          this.$store.commit("OPEN_DROPDOWN");
        }
      },
      closeDropdown: function() {
        this.$store.commit("CLOSE_DROPDOWN");
      }
    }
  }
</script>

USER DROPDOWN LIST

<template>
  <li v-on:click="closeDropdown"><router-link to={{ item.route }} id="button">{{ item.title }}</router-link></li>
</template>

<script>
  export default {
  }
</script>

<style>
</style>

错误:

Property or method "item" 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.

Error in render: "TypeError: Cannot read property 'title' of undefined"

任何人都明白我做错了什么?

1 个答案:

答案 0 :(得分:1)

您未将item作为道具传递给UserDropdownList

首先,将项目作为道具传递给UserDropdownList

<template>
  <UserDropdownList v-for="item in items" v-bind:item="item"></UserDropdownList>
</template>

然后,设置UserDropdownList以接收项目道具

export default {
    props: ['item']
}