Vue2源码解析-生命周期

发布于:2024-05-30 ⋅ 阅读:(122) ⋅ 点赞:(0)

两个文件,一个html一个js

<body>
    <div id="app">

    </div>
</body>
<script src="./Vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            str: "你好"
        },
        beforeCreate() {
            console.log('beforeCreate', this.$el, this.$data)
        },
        created() {
            console.log('created', this.$el, this.$data)
        },
        beforeMount() {
            console.log('beforeMount', this.$el, this.$data)
        },
        mounted() {
            console.log('mounted', this.$el, this.$data)
        },
        beforeUpdate() {
            console.log('beforeUpdate', this.$el, this.$data)
        },
        updated() {
            console.log('updated', this.$el, this.$data)
        },
        beforeDestroy() {
            console.log('beforeDestroy', this.$el, this.$data)
        },
        destroyed() {
            console.log('destroyed', this.$el, this.$data)
        },
    })
</script>
class Vue {
    constructor(options) {
        if (typeof options.beforeCreate === 'function') {
            options.beforeCreate.bind(this)();
        }
        this.$data = options.data;
        if (typeof options.created === 'function') {
            options.created.bind(this)();
        }
        if (typeof options.beforeMount === 'function') {
            options.beforeMount.bind(this)();
        }
        this.$el = document.querySelector(options.el);
        if (typeof options.mounted === 'function') {
            options.mounted.bind(this)();
        }
        // 编译模板...
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到