vue實現curd功能


一、實現效果

二、實現

(一)實現增加用戶功能

Vuserlist組件中

<template>

  <div class="panel panel-default">
    <div class="panel-body">

        <!--<button type="button" class="btn btn-info" @click="addOneUser">添加</button>-->
        <Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用戶</Vbutton>

        <table class="table table-hover">
          <thead>
          <tr class="info">
            <td>用戶名</td>
            <td>密碼</td>
            <td>操作</td>
          </tr>
          </thead>
          <tbody>
          <VuserItem v-for="(item,index) in getAllUserList" v-bind:userinfo="item" v-bind:userid="item.id"></VuserItem>
          </tbody>
        </table>

      <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="myModalLabel">創建用戶</h4>
            </div>
            <div class="modal-body">
              <form id="fm" class="form-horizontal">
                <div class="form-group">
                  <label for="username" class="col-sm-2 control-label">姓名</label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" name="username" placeholder="姓名" v-model="getUsername">
                  </div>
                </div>
                <div class="form-group">
                  <label for="password" class="col-sm-2 control-label">密碼</label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" name="password" placeholder="密碼" v-model="getPassword">
                  </div>
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <span id="errorMsg" style="color: red;"></span>
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary" @click="isSave">保存</button>
              <div class="hidden">
              <el-button :plain="true" @click="open2"></el-button>  <!--保存成功提示-->
              <el-button :plain="true" @click="open4"></el-button> <!--保存失敗提示-->
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>


</template>

<script>
  import VuserItem from '@/components/VuserItem'
  import Vbutton from '@/components/Vbutton'


  export default {
    name: "VuserList",
    data: function () {
      return {

      }
    },
    components: {
      Vbutton,
      VuserItem,
    },
    methods: {
      addOneUser() {
        //修復修改數據后input有默認值的bug
        this.$store.state.UserObject.username="";
        this.$store.state.UserObject.password="";

        $('#addModal').modal('show')
      },

      //保存成功提示函數
      open2(){
        this.$message({
          message: '恭喜你,創建用戶成功!',
          type: 'success'
        });
      },

      //保存失敗提示函數
      open4() {
        this.$message.error('對不起,創建用戶失敗!');
      },


      //發送數據
      isSave(){

        var data={
          //通過計算屬性獲取數據,實際也是從store實例的狀態中拿到數據
          username:this.getUsername,
          password:this.getPassword,
          // csrfmiddlewaretoken: '{{ csrf_token }}'
        };

        //在這個地方觸發對應mutation方法,也就是gaddUser,通過ajax提交所有的數據
        // this.$store.commit(
        //   {
        //     type: 'addUser',
        //     data:data,
        //     getUsername:this.getUsername,
        //     getPassword:this.getPassword,
        //     successfunc: this.open2,
        //     failturefunc:this.open4,
        //   }
        // );

        this.$store.dispatch(
          {
            type: 'addUser',
            data:data,
            getUsername:this.getUsername,
            getPassword:this.getPassword,
            successfunc: this.open2,
            failturefunc:this.open4,
          }
        );

        $('#addModal').modal('hide');//發送成功后模態對話框消失
        this.getUsername=''; //添加成功后將input框置空
        this.getPassword=''
      }


    },
    computed: {

      getAllUserList() {
        return this.$store.state.UserList
      },

      getUsername: {
        set(newValue) {
          this.$store.state.UserObject.username = newValue
        },
        get() {
          return this.$store.state.UserObject.username
        }
      },

      getPassword:{
        set(newValue) {
          this.$store.state.UserObject.password = newValue
        },
        get() {
          return this.$store.state.UserObject.password
        }
      }


    }
  }
</script>

<style scoped>
  table tr td{
    text-align:center;//水平居中
  line-height: 25px;//行高
  vertical-align:middle;//垂直居中
  }
</style>
Vuserlist

這里引入一個按鈕的組件,也就是根據傳入的參數,變成對應的不同cued按鈕:

 <Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用戶</Vbutton>

Vuserlist組件會向按鈕組件傳入它自己的函數名,然后在按鈕組件中執行Vuserlist的方法:

<template>

  <button class="btn" :class="currentBtn" @click="handleClickParent">

    <slot>按鈕</slot>

  </button>

</template>

<script>
    export default {
        name: "Vbutton",
      data:function () {
        return {}
      },
      props:{
        typeBtn:String,
        btnUserMethod:Function
      },
      computed:{
        currentBtn(){
          return {

            'btn-success':this.typeBtn === 'success',
            'btn-warning':this.typeBtn === 'warning',
            'btn-danger':this.typeBtn === 'danger',

          }
        },
        currentMethod(){
          return this.btnUserMethod
        }
      },
      methods:{
        handleClickParent(){
          this.currentMethod();//執行父類方法
        }
      },
    }
</script>

<style scoped>

</style>

上面也就是子組件中執行父組件中的方法,詳情可參考:https://www.cnblogs.com/shenjianping/p/11260397.html

 執行addOneUser方法后彈出模態對話框,添加用戶信息:

    methods: {
      addOneUser() {
        //修復修改數據后input有默認值的bug
        this.$store.state.UserObject.username="";
        this.$store.state.UserObject.password="";

        $('#addModal').modal('show')
      },
    }

當添加數據后執行保存數據,向后台接口發送數據的請求函數:

//發送數據
      isSave(){

        var data={
          //通過計算屬性獲取數據,實際也是從store實例的狀態中拿到數據
          username:this.getUsername,
          password:this.getPassword,
          // csrfmiddlewaretoken: '{{ csrf_token }}'這里目前后端注釋了csrf中間件
        };

        //在這個地方觸發對應mutation方法,也就是gaddUser,通過ajax提交所有的數據

        this.$store.dispatch(
          {
            type: 'addUser',
            data:data,
            getUsername:this.getUsername,
            getPassword:this.getPassword,
            successfunc: this.open2,
            failturefunc:this.open4,
          }
        );

        $('#addModal').modal('hide');//發送成功后模態對話框消失
        this.getUsername=''; //添加成功后將input框置空
        this.getPassword=''
      }

可以看得到這里通過分發的方式,在main.js中執行action的異步操作:

 //用於執行異步函數操作,並且提交的是mutation
  actions:{

    addUser(context,payload){
      $.ajax({
        url:'http://127.0.0.1:8000/api/addUser/',
        method:'post',
        dataType:'JSON',
        contentType: 'application/json', //發送的數據類型為json,所以自己發送的數據必須保證為json
        data:JSON.stringify(payload.data), //發送json數據
        success:function (data) {
          if(data.state){
            payload.successfunc();   //執行保存成功提示函數
          }else {
            payload.failturefunc(); //執行保存失敗提示函數
          }
          //保存返回的數據狀態,mutation修改state狀態,所以傳給mutation處理
          context.commit('ADDUSER',data);
        }

      });
    },
}

這里最后提交的是mutation函數,因為只有mutation可以修改state,修改數據狀態

 mutations: {

    ////action中提交該mutation
    ADDUSER(state,data){
      state.UserList.push(data.user); //將添加成功的數據添加到狀態,用於頁面更新

    },
}

可以看到在store實例中定義的state狀態:

state: {

    //這里面的狀態跟每一個數據屬性有關
    UserList: [],

  },

(二)實現修改用戶功能

在Vuseritem組件中

<template>

  <tr>
    <td>{{userinfo.username}}</td>
    <td>{{userinfo.password}}</td>
    <td>
      <Vbutton typeBtn="danger" @click="delUse" :btnUserMethod="delUse">刪除</Vbutton>
      |
      <Vbutton typeBtn="warning" @click="editUser" :btnUserMethod="editUser">修改</Vbutton>

      <Vmodal :VmodalUserMethod="isdelUser"></Vmodal>


      <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="myModalLabel">修改用戶</h4>
            </div>
            <div class="modal-body">
              <form id="fm" class="form-horizontal">
                <div class="form-group">
                  <label for="username" class="col-sm-2 control-label">姓名</label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" name="username" placeholder="姓名" v-model="getUsername">
                  </div>
                </div>
                <div class="form-group">
                  <label for="password" class="col-sm-2 control-label">密碼</label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" name="password" placeholder="密碼" v-model="getPassword">
                  </div>
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <span id="errorMsg" style="color: red;"></span>
              <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary" @click="isEditSave">保存</button>
              <div class="hidden">
                <el-button :plain="true" @click="open2"></el-button>  <!--保存成功提示-->
                <el-button :plain="true" @click="open4"></el-button> <!--保存失敗提示-->
              </div>
            </div>
          </div>
        </div>
      </div>

    </td>
  </tr>

</template>

<script>
  import Vbutton from '@/components/Vbutton'
  import Vmodal from '@/components/Vmodal'



  export default {
    name: "VuserItem",
    components: {
      Vmodal,
      Vbutton
    },
    data: function () {
      return {

      }
    },

    props: {
      userinfo: {
        type: Object,
        require: true
      },
      userid: {
        type: Number,
        require: true
      },
    },

    computed: {

      getUserId(){

        return this.$store.state.UserId
      },
      getUsername: {
        set(newValue) {
          this.$store.state.UserObject.username = newValue
        },
        get() {
          return this.$store.state.UserObject.username
        }
      },

      getPassword: {
        set(newValue) {
          this.$store.state.UserObject.password = newValue
        },
        get() {
          return this.$store.state.UserObject.password
        }
      }

    },
    methods: {
      delUse() {
        $('#delModal').modal('show');
      },

      editUser() {
        this.$store.state.UserId = this.userinfo.id;
        this.$store.state.UserObject.username = this.userinfo.username;
        this.$store.state.UserObject.password = this.userinfo.password;
        //模態對話框隱藏
        $('#editModal').modal('show');
      },


      isdelUser(open2, open4) {
        console.log(this.userid);

        this.$store.dispatch({
          type: 'delUser',
          data: {id: this.userid},
          successfunc: open2,
          failturefunc: open4,

        });

        $('#delModal').modal('hide');

      },

      //修改成功提示函數
      open2(){
        this.$message({
          message: '恭喜你,修改用戶成功!',
          type: 'success'
        });
      },

      //修改失敗提示函數
      open4() {
        this.$message.error('對不起,修改用戶失敗!');
      },


      isEditSave() {
        console.log(this.getUserId);
        this.$store.dispatch(
          {
            type: 'editUser',
            data: {
              id: this.getUserId,
              username: this.getUsername,
              password: this.getPassword
            },
            successfunc: this.open2,
            failturefunc: this.open4,
          }
        );

        $('#editModal').modal('hide');//發送成功后模態對話框消失

      }

    }

  }
</script>

<style scoped>
  tr td {
    text-align: center;
  / / 水平居中 line-height: 25 px;
  / / 行高 vertical-align: middle; / / 垂直居中
  }
</style>
Vuseritem

按鈕組件:

 <Vbutton typeBtn="warning" @click="editUser" :btnUserMethod="editUser">修改</Vbutton>

點擊修改按鈕執行editUser函數,並且將函數名傳遞給了按鈕,這與增加一樣的效果:

//在methods方法中 
editUser() {
this.$store.state.UserId = this.userinfo.id; this.$store.state.UserObject.username = this.userinfo.username; this.$store.state.UserObject.password = this.userinfo.password; //模態對話框顯示 $('#editModal').modal('show'); },

可以看到在模態對話框顯示前,做了兩件事,第一件事是將用戶id存在store實例中,第二件事是將用戶的默認值填保存起來,實際上下面使用計算屬性獲取input框中的值,其中的getter方法就會獲取默認值,用戶id等值是從父組件Vuserlist傳遞過來的:

 
props: {
      userinfo: {
        type: Object,
        require: true
      },
      userid: {
        type: Number,
        require: true
      },
    },

利用計算屬性獲取默認值以及用戶填寫的值:

computed: {

      getUserId(){

        return this.$store.state.UserId
      },
      getUsername: {
        set(newValue) {
          this.$store.state.UserObject.username = newValue
        },
        get() {
          return this.$store.state.UserObject.username
        }
      },

      getPassword: {
        set(newValue) {
          this.$store.state.UserObject.password = newValue
        },
        get() {
          return this.$store.state.UserObject.password
        }
      }

    },

最后就是發送修改過后的值:

 isEditSave() {
        console.log(this.getUserId);
        this.$store.dispatch(
          {
            type: 'editUser',
            data: {
              id: this.getUserId,
              username: this.getUsername,
              password: this.getPassword
            },
            successfunc: this.open2,
            failturefunc: this.open4,
          }
        );

        $('#editModal').modal('hide');//發送成功后模態對話框消失

      }

剩下的操作就與增加的類似了,這里不再過多贅述,刪除操作也較為簡單。詳情參考github:

三、curd總結

1、綁定屬性與非綁定屬性傳值

綁定的是數據屬性,也就是類似for循環出來的屬性或者data存在的屬性都需要進行綁定

 <VuserItem v-for="(item,index) in getAllUserList" v-bind:userinfo="item" v-bind:userid="item.id"></VuserItem> //userinfo或者userid屬性

而對於非數據屬性不要綁定,直接傳值:

<Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用戶</Vbutton> //類似typeBtn屬性

這兩種綁定與非綁定屬性都可以進行父子傳值

2、獲取input框默認值以及用戶id

  這里碰到的問題就是在VuserList中將每一個用戶id傳給Vitem了,但是在接收后使用過程中,每一個用戶id都是數據表的第一個id,自己也不清楚問什么,但是這里將用戶id接收過后存儲在state狀態中就會正確了,所以將傳遞過來的用戶信息可以完全保存在state中,然后再使用。

const store = new Vuex.Store({
  state: {
    //這里面的狀態跟每一個數據屬性有關
    UserList: [],

    UserObject: {
      username: '',
      password: ''
    },
    UserId:""

  }
}

3、子組件調用父組件方法

在父組件中將方法名傳給子組件,然后子組件進行調用

//在父組件中
<Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用戶</Vbutton>

然后子組件Vbutton 調用

<template>

  <button class="btn" :class="currentBtn" @click="handleClickParent">

    <slot>按鈕</slot>

  </button>

      props:{

        btnUserMethod:Function

      },

 computed:{

        currentMethod(){
          return this.btnUserMethod
        }

      },
      methods:{
        handleClickParent(){
          this.currentMethod();  //調用父組件中的方法
        }
      },

4、全局引用jquery

  • 找到webpack.base.conf.js文件

  • 添加配置

  (1)添加參數的第一個位置

//添加全局配置jquery第一個位置
const webpack = require("webpack")

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

  (2)添加參數的第二個位置

  //添加全局配置jquery第二個位置
  plugins: [
    new webpack.optimize.CommonsChunkPlugin('common.js'),
    new webpack.ProvidePlugin({
      jQuery: "jquery",
      $: "jquery"
    })
  ],

 項目詳情參考https://github.com/ShenJianPing0307/vue-curdUser

后台API項目參考:https://github.com/ShenJianPing0307/VueTestAPI


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM