【问题标题】:nuxt.js passing prop to component's inner elementnuxt.js 将 prop 传递给组件的内部元素
【发布时间】:2017-12-03 22:06:48
【问题描述】:

我有一个简单的组件:

<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 绑定到“div.search__index_search-form”而不是输入?为什么 {{fooId}} 的结果是“all”(默认状态),而不是“500”?

【问题讨论】:

    标签: javascript vue.js vuejs2 nuxt.js


    【解决方案1】:

    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" ... >
    

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

    【讨论】:

    • 谢谢,将其声明为道具是解决方案。
    • 非常好的解决方案。还描述了默认值。我不知道那很好!
    猜你喜欢
    • 1970-01-01
    • 2022-11-13
    • 2016-02-11
    • 1970-01-01
    • 2020-05-22
    • 2019-07-25
    • 2020-01-15
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多