vue父子组件通讯--在组件内使用v-for

Vue组件化开发

通过一个表格渲染的例子来讲
首先最终的效果是这样的,通过http通讯拿到后台数据然后通过vue父子组件通讯将数据传到子组件,最后通过v-for结合表格将数据加载出来

vue父子组件通讯--在组件内使用v-for_第1张图片

首先拿到后台数据
然后将response复制给数组
vue父子组件通讯--在组件内使用v-for_第2张图片

 //vue生命周期钩子 :组件实例创建完成dom未生成
                created () {
             this.$http.post(
                        "/authority/manage",
                        {

                        },
                        {headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }}
                    ).then(function(response){
                    this.authorityManages=response.data
                        })
                  },
                  data: function () {
                        return data
                      } 

然后创建子组件

Vue.component('AmContentBody',{
    props: ['items'],   
    template:'<div id="am-content-body" class="row-center">'
        +'<div  style="height:70%;width:60%;overflow:auto">'
                +'<table border="1" class="table table table-striped table-bordered table-hover" style="width:100%"  >'
                +'<thead>'
                +'<tr>'
                +'<th>编号th>'
                +'<th>用户名th>'
                +'<th>密码th>'
                +'<th>权限th>'
                +'<th>有效期限th>'
                +'<th>编辑th>'
                +'<th>登入登出信息th>tr>thead>'
            +'<tbody  >'
            +'<tr v-for="item  in items" > <th >{{item.user_num}}th><th>{{item.sys_name}}th>'
            +'<th>{{item.password}}th><th>{{item.power_value}}th><th>{{item.power_term}}th>'
            +'<th><button style="height:100%;width:100% ;background-color:#FFFFCC ;border:none;outline:none" @click="updateInfo(item)">编辑button>th>'
            +'<th><button style="height:100%;width:100% ;background-color:#FFFFCC ;border:none;outline:none" >查看button>th>'
            +'tr>'
            +'tbody>'
            +'table>div>div>', 

在父组件中将子组件要用的数据:props: [‘items’]传进来

const authoritymanage={
         template:'<div class="content">'
                +'<ContentHeat >ContentHeat>' 
                +'<AmContentBody   :items=this.authorityManages   >AmContentBody>'
                +'<AmContentBottom >AmContentBottom>'
                +'<AuthorityInfo>AuthorityInfo>div>',

因为数组是动态数组,所以父组件用 v-bind将数据传入

 :items=this.authorityManages   

子组件用 props来接受从父组件传入的数据

props: ['items'],

authorityManages 是我们接受response数据的数组
将数组传入子组件后,用v-for循环加载数据,

v-for="item  in items"

然后在表单中逐一循环渲染

<th>{{item.sys_name}}th>

所以因为组件有自己独立的作用域,而vue中父子组件的通讯是单向的,如果你在子组件内修改使用子组件之外的数据 vue会报警告

小伙伴们,不用直接拿代码贴上去用哈,里面有很多私有变量,可能会乱掉,
看懂了应该就可以自己写啦

你可能感兴趣的:(前端)