1. 程式人生 > 程式設計 >Vue自巢狀樹元件使用方法詳解

Vue自巢狀樹元件使用方法詳解

本文例項為大家分享了自巢狀樹元件的使用方法,供大家參考,具體內容如下

效果圖

Vue自巢狀樹元件使用方法詳解

注意事項

  • 元件自巢狀,定義名稱時就定義為元件名
  • 單選和多選使用者時,以最頂級父元件的屬性為準,由於元件內不能同步修改prop,故採用data註冊另一個同類型數值用於接收元件內改變,並使用update,同步更新到prop上
  • 展開元件才開始載入使用者列表
<template>
  <ul v-show="isShow" ref="user-tree">
    <li v-for="(item,idx) in userList" :key="idx">
; <div> <!-- 多選使用者樹 --> <input class="primary" type="checkbox" v-model="selectUsers1" :value="item.userId" v-show="isCheck" /> <!-- 單選使用者樹 --> <span @click="onSelect(item)" :style="{ color: selectUser1 == item.userId ? 'red' : '',cursor: 'pointer',}" > xBxEkekhN
<i class="iconfont icon-user"></i> {{ item.userName }}</span > <!-- 展開使用者樹 --> <i class="iconfont icon-right" v-if="item.haveChild" @click="expandItem(idx)" ></i> </div> <!-- 巢狀使用者樹 --> <user-tree :user-id="item.userId" v-if="item.haveChild" :is-show.sync="item.isShow" :select-user.sync="selectUser1" :select-users.sync="selectUsers1" :is-check="isCheck" ></user-tree> </li> </ul> </template> <script> export default { name: "user-tree",//定義為元件名,否則自巢狀時報未註冊自身元件錯誤 props: { isShow: {//是否展開使用者列表 type: Boolean,default: false },userId: {//當前使用者樹父級id type: Number,default: 0 },selectUser: {//當前選中的使用者id type: Number,default: 0客棧
},selectUsers: {//多選使用者 type: Array,default: function () { return []; } },isCheck: {//是否多選功能 type: Boolean,default: false } },data: () => ({ userList: [],//使用者列表 selectUser1: 1,//單選使用者 selectUsers1: [],//多選使用者 isLoad: true }),watch: { selectUser1 () {//單選使用者,當前級同步到父級 if (this.selectUser1 != this.selectUser) { this.$emit("update:select-user",this.selectUser1); } },selectUser () {//單選使用者,當前級同步於父級 if (this.selectUser1 != this.selectUser) { this.selectUser1 = this.selectUser; } },selectUsers1 () {//多選使用者,當前級同步到父級 if (this.selectUsers1 != this.selectUsers) { this.$emit("update:select-users",this.selectUsers1); } },selectUserxBxEkekhNs () {//多選使用者,當前級同步於父級 if (this.selectUsers1 != this.selectUsers) { this.selectUsers1 = this.selectUsers; } },isShow () { if (this.isShow) { this.getUserList(); } } },methods: { onSelect (item) {//單選使用者 this.$emit("update:select-user",item.userId); },expandItem (idx) {//展開使用者樹 if (this.userList[idx].isShow) { this.userList[idx].isShow = false; } else { this.userList[idx].isShow = true; } },getUserList () { var list = []; for (var i = 0; i < 10; i++) { var userId = Math.round(Math.random() * 10000); list.push({ userId: userId,userName: "user-" + userId,haveChild: i % 2,//是否有子樹 isShow: false //是否展示子樹 }); } this.userList = list; },},mounted () { if (this.userId == 1) {//當前父級userId為根使用者id,就載入並展開使用者樹 this.getUserList(this.userId); } } }; </script>

使用樹元件

<div>{{ selectUser }}</div>
    <div>
      <span v-for="item in selectUsers" :key="item">【{{ item }}】</span>
    </div>
    <user-tree
      :user-id="1"
      :is-show="true"
      :select-user.sync="selectUser"
      :select-users.sync="selectUsers"
      :is-check="true"
></user-tree>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。