如何将数组长度传递给vue.js中的另一个组件(从子组件到父组件)?

xmq68pz9  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(278)

我有两个组件dashboard.vue(父级)和displaybooks.vue(子级)。在子组件中,我有一个数组addedbooks:[]当用户单击AddtoBag按钮时,它应该增加,当用户单击AddtoBag按钮时,它应该减少,直到现在为止,它工作正常,现在我的要求是addedbooks.length(数组长度)应该从displaybooks.vue传输到dashboard.vue组件。如何实现这一点请帮助我 Dashboard.vue ```

    <ul class="nav navbar-nav navbar-right" id="right-bar">
        <li><a> <i class="far fa-user"></i></a></li>
        <p class="profile-content">profile</p>
        <li><a><i class="fas fa-cart-plus"></i></a></li>
        <p class="cart-content">cart</p>
    </ul>
</div>
<div class="mid-body">
    <h6>Books<span class="items">(128items)</span></h6>

    <select class="options" @change="applyOption">
        <option disabled value="">Sort by relevance</option>
        <option value="HighToLow">price:High to Low</option>
        <option value="LowToHigh">price:Low to High</option>
    </select>
</div>

<div v-if="flam==false">
    <h2>Hello</h2>
</div>

<DisplayBooks v-show="flag==='noOrder'" />
<sortBooksLowtoHigh v-show="flag==='lowToHigh'" />
<sortBooksHightoLow v-show="flag==='highToLow'" />

`DisplayBooks.vue`

bf1o4zei

bf1o4zei1#

观察阵列更改并将其长度发送到父阵列:
displaybooks.vue

data() {
        return {

            flag: true,
            state: true,
            addedBooks:[], // this array length should be passed to dashboard component
            clickedCard: '',
            books: [{
                id: 0,
                file: 'https://images-na.ssl-images-amazon.com/images/I/41MdP5Tn0wL._SX258_BO1,204,203,200_.jpg',
                name: 'Dont Make me think',
                author: 'Sai',
                price: '1500'
            }, ]
        }
    },
watch:{
    addedBooks:{
            handler(val){
               this.$emit('update-books-count',val.length)
             },
             deep:true
          }

}

Jmeter 板

<ul class="nav navbar-nav navbar-right" id="right-bar">
            <li><a> <i class="far fa-user"></i></a></li>
            <p class="profile-content">profile</p>
            <p>{{booksCount}}</p>
            <li><a><i class="fas fa-cart-plus"></i></a></li>
            <p class="cart-content">cart</p>
        </ul>
...
 <DisplayBooks v-show="flag==='noOrder'" @update-books-count="(n)=>booksCount=n"/>
...
  data() {
        return {
            booksCount:0,
            flag: 'noOrder',
            brand: 'Bookstore',
            name: '',
            flam: true,
            visible: true,
            books: [{

            }]
        }
    },

相关问题