nuxt.js将prop传递给组件的内部元素

时间:2017-12-03 22:06:49

标签: javascript vue.js vuejs2 nuxt.js

我有一个简单的组件:

<template>
    <div id="search__index_search-form">
        <input :foo-id="fooId" @keyup.enter="findFoos()" type="text" :value="keyword" @input="updateKeyword"
               placeholder="Search for a foo">
        <button @click="findFoos()">Search!</button>
        {{fooId}}
    </div>
</template>

<script>
    import {mapState} from "vuex";

    export default {
        computed: mapState({
            keyword: state => state.search.keyword
        }),
        data: function () {
            return {fooId: "all"};
        },
        methods: {
            updateKeyword(e) {
                this.$store.commit("setSearchKeyword", e.target.value);
            },
            findFoos() {
                this.$store.dispatch("findFoos");
            }
        }
    };
</script>

我从nuxt页面调用它:

<template>
    <searchbar v-bind:fooId="500"/>
</template>
<script>
    import searchBar from "~/components/search-bar.vue";

    export default {
        components: {
            'searchbar': searchBar
        }
    };
</script>

这导致:

<div id="search__index_search-form" fooid="500"><input shop-id="all" type="text" placeholder="Search for a foo"><button>Search!</button>
      all
</div>

问题是,为什么fooId绑定到&#34; div.search__index_search-form&#34;而不是输入?为什么{{fooId}}会导致&#34;所有&#34; (默认状态),而不是&#34; 500&#34;?

1 个答案:

答案 0 :(得分:2)

fooIddiv#search__index_search-form上呈现,因为您未将fooId声明为组件的属性。 Vue的默认行为是在组件的根元素上呈现未声明的属性。

您需要将fooId声明为属性。

 export default {
    props: {
      fooId: {type: String, default: "all"}
    },
    computed: mapState({
        keyword: state => state.search.keyword
    }),
    methods: {
        updateKeyword(e) {
            this.$store.commit("setSearchKeyword", e.target.value);
        },
        findProducts() {
            this.$store.dispatch("findFoos");
        }
    }
};

我不确定你到底想要完成什么。

<input :foo-id="fooId" ... >

这段代码似乎没有任何意义。

相关问题