javascript - Reuse issues using mixin components in vue
仅有的幸福
仅有的幸福 2017-06-14 10:53:39
0
3
898

Briefly describe the scenario, such as a.component and b.component will use the following code,

import axios from 'axios';
export default(){
    data(){
        return {
            initList: [],
            pageSize: 10,
            pageNo: 1
        }
    },
    created(){
        this.initList();
    },
    methods: {
        initList(){
            axios({
                url: '/list1',
                data: {}
            })
            .then(res => res.data)
            .then(data => {
                this.initList = data;
            })
        },
        pageSizeChange(size){
            this.pageSize = size;
            this.initList();
        },
        pageNoChange(pageNo){
            this.pageNo = pageNo;
            this.initList();
        }
    }
}

After using this code, the two components only request different URLs when communicating. How to use mixin reuse, CaiGou please give me some advice~

仅有的幸福
仅有的幸福

reply all(3)
世界只因有你

The only difference you have is the url, so you can just define the url as the data attribute. Add the data attribute url to your mixin, and then define the url in the a and b components respectively, which will overwrite the url in the mixin, as follows:

mixin:

import axios from 'axios';
export default(){
    data(){
        return {
            url: '', // 看这里!
            initList: [],
            pageSize: 10,
            pageNo: 1
        }
    },
    created(){
        this.initList();
    },
    methods: {
        initList(){
            let url = this.url;
            axios({
                url: url,
                data: {}
            })
            .then(res => res.data)
            .then(data => {
                this.initList = data;
            })
        },
        pageSizeChange(size){
            this.pageSize = size;
            this.initList();
        },
        pageNoChange(pageNo){
            this.pageNo = pageNo;
            this.initList();
        }
    }
}

a:

export default(){
    mixins: [引入mixin],
    data(){
        url: '这里是a中的url'
    }
}

b is defined in the same way as a

習慣沉默

Put the repeated code into mixin.js, and write the non-duplicated initList() in each component separately

过去多啦不再A梦

What I’m thinking about now is

initList () {
    let url = ''
    // 这个地方写个判断
    if (条件a){
        url = ...
    } else {
        url = ...
    }
    axios({
        url: url,
        data: {}
    })
}

No need to change anything else. As for judging how to write, just write it yourself based on the difference between the two pages.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template