实用技巧

1.view层更新后进行操作

this.$nextTick(() => {

})

2.watch深度监听

data() {
    return {
        info: Object
    }
},
watch: {
    info: {
        handler(val) {
            console.log(val)
        },
        deep: true
    }
}

3.watch监听对象中的某个属性

data() {
    return {
        info: {
            name: ''
        }
    }
},
watch: {
    'info.name': (val) => {
        console.log(val)
    }
}

4. 阻止路由跳转

data() {
    return {
        isShow: false
    }
},
beforeRouteLeave(to, from, next) {
    if (isShow) {
        next() // 继续执行
    }
}

5.APP中点APP自带返回按钮时不关闭页面,而是路由回退

// app.vue
created() {
    history.pushState(null, null, document.URL)
    window.addEventListener('popstate', () => {
        // history.pushState(null, null, document.URL)
    })
}

6.vue methods的方法中定义函数

data() {
    return {
        test: 0
    }
},
mounted() {
    this.add()
},
methods: {
    add() {
        var that = this
        function test() {
            console.log('test')
            that.test ++
        }
        test()
    }
}

7.vue方法暴露给外部

mounted: function () {
    //此方法绑定到window下面,提供给外部调用
    window['showAdd'] = () => {
      this.showAdd()
    }
}
// 外部调用
window.showAdd()

8. Vue 不能检测到对象属性的添加或删除

this.$set(object, key, value)

9. Vue 不能检测以下变动的数组

this.$set(arr, index, newValue)

Last updated