Vue编码习惯(一)

631 阅读2分钟

1. beforeCreate 与 created

不要在beforeCreate里面,改data里面的数据或者调取接口。 在beforeCreate里面改动data里面的数据,不会成功。 在beforeCreate里面调用methods里面定义的方法也一定会报错。

在beforeCreate里面调用后台接口,使用在methods里面定义的方法一定会报错。在beforeCreate的时候,默认方法和所有元素是没有被渲染出来的,所以要定义初始化数据不要在beforeCreate中进行。

beforeCreate最好不要改动data里的数据,否则可能会出现无法监听的情况,模板中需要使用data进行渲染时,先给data默认的初始值,created之后再进行更改(如ajax)改成需要的值。

例子:

export default {
    data(){
        return {
            isShowFirst: false,
            isShowSecond: false
        }
    },
    beforeCreate(){
        this.isShowFirst = true  //->在beforeCreate里面, 更改data的数据不成功
        this.test()  //->Error in beforeCreate hook: "TypeError: this.test is not a function"  
        //->在beforeCreate里面调用methods里面定义的方法会报错
    },
    created (){
        this.isShowSecond = true //->在created里面, 更改data的数据会成功
        this.test() //->1
        //->在created里面调用methods里面定义的方法会成功
    },
    mounted(){
        console.log('isShowFirst:', this.isShowFirst)  //->false
        console.log('isShowSecond:', this.isShowSecond)  //->true
    },
    methods:{
        test(){
            console.log(1)
        }
    }
}

一般在created里面调取后台接口,或者改动data里面的数据。

2. Vuex数据更新,页面数据没有跟着刷新。

在 ajaxRequest.js 配置的全局Loading,在页面刷新的时候,去更改mutation中的 isShowLoading 时,页面的 isShowLoading 没有跟着刷新。

需要把 isShowLoading 放在计算属性里面去获取,然后通过watch来监听,这样每次Vuex有更新就能同步到视图了。

store/index.js :

const store = new Vuex.Store({
    state:{
        //->Loading效果是全局的,应该写在Vuex里面
        isShowLoading: false
    },
    mutations: {
        //->在mutations里面去更改公共状态
        
        //->显示Loading
        showLoading(state) {
            state.isShowLoading = true
        },
        //->隐藏Loading
        hideLoading(state) {
            state.isShowLoading = false
        }
    }
})
export default store

ajaxRequest.js:

import store from '../store'

//->判断队列
if (Object.keys(this.queue).length === 0) {
    //->第一次请求,显示Loading
    store.commit('showLoading')
}

App.vue:

import { mapState } from 'vuex';

computed: {
    ...mapState(['isShowLoading'])
},
watch:{
    //->观察Vuex里面的isShowLoading
    isShowLoading(newVal) {
        console.log('isShowLoading newVal:', newVal)
        if (newVal) { //->如果为true
            console.log('打开全局Loading')
            this.$dialog.loading.open('加载中')
            setTimeout(() => {
                this.$dialog.loading.close()
            }, 5000)
        } else {
            //->当变为false时,立马关闭Loading
            console.log('关闭全局Loading')
            this.$dialog.loading.close()
        }
    },
}

这样,当更改Vuex里面的state时,就会同步到视图了。