vue搭配antD-Vue開發項目(一)


安裝antd-vue並按需加載(詳見 https://www.antdv.com/docs/vue/use-with-vue-cli-cn/ )

1、yarn add ant-design-vue
2、yarn add babel-plugin-import
3、babel.config.js文件
module.exports = {
  presets: ["@vue/app"],
+  plugins: [
+    [
+      "import",
+      { libraryName: "ant-design-vue", libraryDirectory: "es", style: "css"}  //注意官網這里是style:true,這可能會導致報錯。建議使用style:"css"
+    ]
+  ]
};
4、src/main.js
import {Button,Switch} from 'ant-design-vue'
Vue.use(Button).use(Switch)
5、使用
<a-button type="primary">哈哈哈</a-button>
<a-switch defaultChecked />

若不想按需加載antd-vue,想一次性全部引入

以上第3步:
將:{ libraryName: "ant-design-vue", libraryDirectory: "es", style: "css"}
改為:{ libraryName: "Antd", libraryDirectory: "es", style: "css"}  //提醒:這里style:"css"可改為style:true且不會報錯,這樣改后會加載包里的less文件而非css文件。不改也沒影響

以上第4步:全部改為
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
Vue.use(Antd);

然后重啟項目即可,請務必重啟項目。

antd表格的使用(包括自定義表格列,表格分頁,vue中的對象格式與react的不同)

<template>
<a-table 
    :columns="columns"    //2、綁定columns,提醒:columns不僅要自定義,而且之后還需要在data里注冊
    :dataSource="personList" 
    bordered 
    :rowKey="record=>record.pid"   //4、表格的每一列必須有一個key值
    :pagination="false"   //7、不使用表格的分頁,分頁設置建議單獨用分頁組件,提高靈活性
>
    <div slot="pimg" slot-scope="text,record">   //6、通過slot='pimg'綁定。通過slot-scope="text,record"可以動態獲取數據給自定義的標簽,但前提是必須在columns里配置了scopedSlots
        <img :src="record.pimg"/>
        <a-button @click="bigImg(record.pimg)">查看大圖</a-button>
    </div>
    <div slot="operations" slot-scope="text,record">
        <a-button @click="personEdit(record.pid)">編輯</a-button>
        <a-popconfirm :title='`確定刪除人物"${record.pname}"的信息?`' okText="確定" cancelText="取消" @confirm="deletePerson(record.pid)">
            <a-button>刪除</a-button>
        </a-popconfirm>            
    </div>
</a-table>
 <div style="margin-top:20px;textAlign:right">  //單獨使用分頁組件
    <a-pagination 
        v-model="pagination.page" 
        :pageSize="pagination.pageSize" 
        :total="pagination.total" 
        @change="pageChange"  
    />
</div>
</template>

<script>
const columns = [   //1、定義表格Header數據columns
    {
        title: '姓名',
        dataIndex: 'pname',  //此處命名有講究,要與渲染的數組里的屬性名一致(如personList里是pname,這里就要用pname,不可用cname,name等)
        key:'pname',
    },
    {
        title: '圖片',
        dataIndex: 'pimg',
        key:'pimg',
        scopedSlots:{customRender:'pimg'},  //5、這里設置了scopedSlots:{customRender:'pimg'}之后,表格部分即可通過slot='pimg'綁定,然后去自定義標簽及樣式。並可通過sloct-scope獲取動態數據
    },
    {
        title:'操作',
        dataIndex:'operations',
        key:'operations',
        scopedSlots:{customRender:'operations'},   
    }
];

export default {
    name:'Demo',
    data(){
        return{
            personList:[],   //人物列表數據
            columns,   //3、這里必須注冊columns
            pagination:{   //9、分頁配置(這是一個對象格式的數據)
                page:1,
                pageSize:10,
                total:10,  //這里total隨便設一個大於0的數即可,后續在接口里會重新賦值
            }
        }
    }, 
    created(){
        //進入此頁面后,獲取上次記錄的分頁,從而獲取上次記錄的分頁的數據
        if(sessionStorage.getItem('personPage')){
            this.pagination.page=JSON.parse(sessionStorage.getItem('personPage'))
        }
        this.getPersonList()
    }
    methods:{
        //初始化時獲取列表數據
        getPersonList(){
            let params={
                page:this.pagination.page,
                pagesize:this.pagination.pageSize
            }
            this.$axios.get(`${common.base}/admin/getPersonList`,{params}).then(res=>{
                if(res.data.code==200){
                    if(res.data.data.list){
                        this.personList=res.data.data.list
                        this.pagination.total=res.data.data.allsize
                    }
                }else if(res.data.code==401){
                    this.$message.warning("登錄超時,請重新登錄!")
                    this.$router.push({name:'Login'})
                }
            }).catch(err=>{})
        },
        //翻頁時執行此函數
        pageChange(page,pageSize){   //10、分頁函數
            sessionStorage.setItem('personPage',page)  //將當前分頁存進session,以便在下次再進入此表格時自動回到當前分頁
            let params={
                page:page,
                pagesize:pageSize
            }
            this.$axios.get(`${common.base}/admin/getPersonList`,{params}).then(res=>{
                if(res.data.code==200){
                    if(res.data.data.list){
                        this.personList=res.data.data.list
                    }
                }
            }).catch(err=>{})
        },
        //刪除人物
        deletePerson(pid){
            this.$axios.post(`${common.base}/delPerson?pid=${pid}`).then(res=>{
                if(res.data.code==200){
                    this.$message.success(`人物 ${pname} 信息刪除成功!`)

                    //判斷若列表數據只有一條且當前頁不是第一頁,則執行page-1,已達到當前分頁最后一條數據被刪除后,自動跳轉至上一分頁的效果
                    if(this.personList.length==1&&this.pagination.page>1){
                        this.pagination.page-=1
                        sessionStorage.setItem('personPage',this.pagination.page)  //將當前分頁存進session,以便在下次再進入此表格時自動回到當前分頁
                    }

                    this.getPersonList()   //刪除成功后調用此函數獲取人物列表信息
                }
            }).catch(err=>{})
        },
    }      
}
</script>
vue中對象方式和react的不同:vue中 :pagination="{page:1,pageSize:10,total:0}"   react中 pagination={{page:1,pageSize:10,total:0}}  區別:vue中需要v-bind綁定,且包裹方式是""。

解決瀏覽器緩存導致異步請求后頁面不更新的問題

一般在請求靜態資源的時候,瀏覽器檢測不是新數據的話,則會從緩存中讀取而不會去進行更新,從而導致后台提交數據后前台不更新的問題。
解決方法1:ctrl+shift+delete呼出瀏覽器緩存選項,清除緩存即可。但這樣的操作對用戶不友好,不推薦
解決方法2:控制台中Network里選中Disable cache使瀏覽器不保存緩存,僅適合開發人員用。
解決方法3:在請求接口的時候帶上隨機數或者時間戳即可(推薦使用)
getContent(content){
    this.$axios.get(`${common.base}/getDemoList?t=${Math.random()}`).then(res=>{   //添加隨機數 `t=${Math.random()}` 或 時間戳 `t=${new Date().getTime()}`
        this.demoList=res.data.list
    }).catch(err=>{})
},

router路由在新窗口打開頁面

goIndex(){
    let goIndex=this.$router.resolve({name:'Index'})   //這里要用resolve方式。 push,go方式無效
    window.open(goIndex.href,'_blank')
}

解決vue路由跳轉報錯

原因:據翻看大佬的解釋,vue-router ≥3.0版本回調形式以及改成promise api的形式了,返回的是一個promise,如果沒有捕獲到錯誤,控制台始終會出現如圖的警告

解決:在pages/router/router.js  即路由頁面添加以下代碼
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
+ const routerPush = VueRouter.prototype.push
+ VueRouter.prototype.push = function push(location) {
+   return routerPush.call(this, location).catch(error=> error)
+ }

轉換時間

        transDate(dateNum){
            let date=null
            if(dateNum){
                date=new Date(dateNum)
            }else{
                date=new Date()
            }
            let Y=date.getFullYear()
            let M=date.getMonth()+1
            M=M<10?('0'+M):M
            let D=date.getDate()
            D=D<10?('0'+D):D
            let h=date.getHours()
            h=h<10?('0'+h):h
            let m=date.getMinutes()
            m=m<10?('0'+m):m
            let s=date.getSeconds()
            s=s<10?('0'+s):s

            this.releaseTime=`${Y}-${M}-${D} ${h}:${m}:${s}`
            
        },

antd回到頂部功能的使用,更改監聽的元素(組件默認的監聽對象是window,這里我們更改成其他元素)

<div class="go_top_content">
    <a-back-top :target="getScrollElem" :visibilityHeight="1000">  //定義一個getScrollElem函數用來更改“回到頂部組件”監聽的元素
          <span class="iconfont icon4fanhuidingbubai"></span>
    </a-back-top>
</div>

getScrollElem(){
    return document.getElementById('book_info')  //監聽id為book_info的元素的滾動
},

使用DatePicker 日期選擇框組件 https://www.cnblogs.com/huihuihero/p/13093253.html


免責聲明!

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



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