You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将原生JavaScript编写的Cal日历类导入Vue组件中正常运行

该需求完全可以实现,操作步骤如下:

步骤1:调整原生日历JS文件

你当前的JS文件末尾有自动实例化执行的代码,导入Vue时会在DOM未渲染完成时提前执行,导致找不到容器元素报错,需要做两处修改:

  • 删除末尾的自动实例化代码
  • 导出Cal类供Vue组件引入

修改后的JS文件末尾部分参考:

// 删掉原来下面这三行自动执行的代码
// const containerId = 'renderhere';
// let calendarInstance = new Cal(new Date(), containerId);
// calendarInstance.render()

// 新增导出语句
export default Cal

步骤2:修改Vue组件代码

需要在Vue的mounted生命周期钩子中初始化日历实例,此时模板中的DOM已经完成挂载,能正常获取到#renderhere容器:

<template>
    <div class="container-fluid">
        <div class="container-fluid">
      <div class="row" >
          <div class ="col-3">
          </div> <!-- Left Column-->
        <div class="col-6">
            <h2 class="display-8" id ='whiteWrite'>Make a Reservation</h2>
                <div id ='renderhere'>space for calender</div>
                <div class="row">
                    <div class=col>
            </div>
            </div>
            <div id ='hide'> TODO: Graph </div>
        </div> <!-- Middle Column-->

        <div class = "col-3"> 

        </div> <!-- Right Column-->
      </div>
    </div> <!-- Calender Div-->
    </div>
</template>

<script> 
// 路径替换成你实际的日历JS文件路径
import Cal from './你的日历JS文件路径.js'
export default {
    name: "Fred",
    data() {
        return {
            calendarInstance: null
        }
    },
    mounted() {
        // 此时DOM已渲染完成,可以正常初始化日历
        this.calendarInstance = new Cal(new Date(), 'renderhere')
        this.calendarInstance.render()
    },
    beforeUnmount() {
        // 组件销毁前清理容器内容,避免内存泄漏
        if (this.calendarInstance) {
            document.getElementById('renderhere').innerHTML = ''
            this.calendarInstance = null
        }
    }
}
</script>

<style scoped>
/* 如果要给日历写样式,需要加深度选择器才能生效,示例如下 */
::v-deep #month {
  /* 你的自定义样式 */
}
::v-deep .day {
  /* 你的自定义样式 */
}
</style>

常见问题说明

  • 如果样式不生效:因为scoped样式只会作用于Vue模板中直接写的元素,原生JS动态创建的元素需要加::v-deep(Vue3)或/deep/(Vue2)深度选择器前缀,也可以把日历相关样式放到全局样式文件中。
  • 如果还有找不到容器的报错:检查JS文件的自动执行代码是否完全删除,确保只有在mounted钩子中才会执行new Cal初始化逻辑。

内容的提问来源于stack exchange,提问作者Drew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 14:36:04