组件和$emit传值

2020-05-19  本文已影响0人  琳媚儿

例:
组件分解
定义一个名为header-from 的新组件

<div id="app">
 <header-from></header-from>
</div>

将template 模板中的内容提出了( type="text/x-template" )

 <script type="text/x-template" id="header-add-from">
       <form></form>
   </script>
    Vue.component('header-from', {         
            template: 'header-add-from ',
        })

事件抛出一个值$event

@addfruit="addfruitChange($event)"

当在父级组件监听这个事件的时候,我们可以通过 $event 访问到被抛出的这个值

<div id="app">
        <header-from @addfruit="addfruitChange($event)"></header-from>
        <div>
            <ul v-for="item in items" :key="item.id">
                <li>
               
                </li>
            </ul>

        </div>
    </div>

this.$emit('addfruit',fruit) 触发一个名字为'addfruit'的事件,抛出fruit 事件,此案例中fruit事件中包含的时输入框中新增数据

<script>
 Vue.component('header-from', {         
            template: '#header-add-from',
            methods: {
                addData: function (items) {
                    let fruit={
                       id: ++maxId,
                        name:this.$refs.fruitname.value,
                        price:this.$refs.fruitprice.value
                    }
                    this.$emit('addfruit',fruit)    
                    console.log(fruit);
                                   
                }
            }
        })
</script>

触发addfruitChange()事件时,将fruit数据放入items数组中

new Vue({
            el: '#app',
            data: {
                items: []
            },
            created() {
                fetch('http://localhost:3000/test')
                    .then(res => res.json())
                    .then(data => {
                        this.items = data
                    })
            },
            methods:{
                addfruitChange:function(fruit){
                    let p=fruit;
                    this.items.push(p)
                }
            }
        })

逻辑代码v-if:

定义一个组件,判断 ,详情页不等于null 就显示,等于null就隐藏:
@click="showDetail(product)" 触发事件时

<div id="app">
        <table>
            <tbody v-for="(product,index) in products" :key="index">
                <tr @click="showDetail(product)"></tr>
            </tbody>
        </table>

 <detail-from v-if="currentDetail!=null" @hide-me="currentDetail=null" :product="currentDetail"></detail-from>
</div>
  <script type="text/x-template" id="detail-show">
        <button @click="$emit('hide-me')">隐藏</button><br>
  </script>
    <script>
        Vue.component('detail-from', {
            template: '#detail-show',
            props: ['product']
        })
    </script>
<script>
  new Vue({
           el: '#app',
           data: {
                currentDetail: null,
                products: []
         },
   methods: {
                showDetail: function (product) {
                    //让数据等于null 隐藏
                    this.currentDetail = product
                    // console.log(showDetail);
                },
            }
})
</script>
上一篇 下一篇

猜你喜欢

热点阅读