vue实现数据的添加功能

  • Post author:
  • Post category:vue
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/vue.min.js"></script>
    <script src="/vue-resource.min.js"></script>
    <style>
        #th th{
            background-color: #50a9fa;
            color: aliceblue;
            font-size: large;
        }
    </style>
</head>
<body >
<div id="app" align="center">
    <input type="text" v-model="pname">
    <button @click="addData">添加数据</button>
    <table id="th" border="1"solid width="400px">
        <tr>
            <th>编号</th>
            <th>名称</th>
            <th>时间</th>
            <th>操作</th>
        </tr>
        <tr v-for="item in list ">
            <td>{{item.id}}</td>
            <td>{{item.name}}</td>
            <td>{{item.ctime}}</td>
            <td>
                <a href="javascript:void(0)" >删除</a>
            </td>
        </tr>
    </table>
</div>
<script>
    //vue的生命周期
    
    new Vue({
       el:'#app',
        data:{
           pname:"",
           list:[]
        },
        //vue对象实例创建成功之后就会自动调用这个方法
        //如果你想写的方法在舒适化的时候就被调用的话就要要用到created这个
        created:function () {
          this.getlist();//这里定义这个方法,vue实例之后运行到这里就调用这个函数
        },
        methods:{
            addData:function () {
            //实现将数据post到数据添加接口
                //获取用户填写的文本框的值,只需要通过this.pname
                var postData={name:this.pname};
                var options={emulateJSON:true};
                this.$http.post('http://vueapi.ittun.com/api/getprodlist',postData,options).then(function (response) {
                    if(response.body.status!=0)
                    {
                        alert(response.body.message);
                        return ;
                    }
                    //将文本框中的值清空
                    this.pname="";
                    //直接将列表数据重新加载一次
                    this.getlist();//局部刷新一下
                });

            },
            getlist:function () {
                //请求服务器的api获取到品牌的数据列表
                this.$http.get('http://vueapi.ittun.com/api/getprodlist').then(function (response) {
                    //处理服务器异常信息提示
                    if(response.body.status!=0)
                    {
                        alert(response.body.message);
                        return ;
                    }
                    //处理正常的逻辑数据处理
                    this.list=response.body.message;
                    
                });
                

            }
            
        }
    });
</script>
</body>
</html>