javascript - 如何在 vue 组件中渲染原生 javascript?
问题描述
我正在使用一个用本机 javascript 编写的库,我需要将其导入到 vue 组件中才能呈现。我不知道我做错了什么
import { RowSelection } from 'gridjs-selection'
import { h, Grid, Row } from 'gridjs'
import Switcher from '@/components/Switcher.vue'
import http from '@/http-common'
const grid = new Grid({
columns: ['Name', 'Email', 'Phone Number'],
data: [
['John', 'john@example.com', '(353) 01 222 3333'],
['Mark', 'mark@gmail.com', '(01) 22 888 4444']
]
}).render(document.getElementById('table'))
export default grid
我的组件
<template>
<div class="container">
<div class="row">
<div class="col-12">
<div id="table"></div>
</div>
</div>
<div id="test"></div>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import gridJs from '@/components/integration/IntegrationsTableJs'
export default Vue.extend({})
</script>
<style></style>
解决方案
您试图在渲染之前获取元素。您的自定义脚本在其导入时执行,但在页面中呈现元素之前。您可以使用 Vue 的生命周期钩子。
但在此之前,您需要对自定义脚本进行一些小改动,以便可以在需要时调用它。基本上,您需要将自定义逻辑包装在一个方法中。
import { RowSelection } from 'gridjs-selection'
import { h, Grid, Row } from 'gridjs'
import Switcher from '@/components/Switcher.vue'
import http from '@/http-common'
const grid = () => { new Grid({
columns: ['Name', 'Email', 'Phone Number'],
data: [
['John', 'john@example.com', '(353) 01 222 3333'],
['Mark', 'mark@gmail.com', '(01) 22 888 4444']
]
}).render(document.getElementById('table')) }
export default grid
在此处阅读有关导出的更多信息
mounted
现在在你的 Vue 组件中,你可以在钩子中调用这个方法。在此处阅读有关 Vue 生命周期钩子的信息
<template>
<div class="container">
<div class="row">
<div class="col-12">
<div id="table"></div>
</div>
</div>
<div id="test"></div>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import gridJs from '@/components/integration/IntegrationsTableJs'
export default Vue.extend({
// life-cycle hook.
mounted: function() {
gridJs();
// if you want sexy code; try passing the reference to the "table" element as a parameter from here.
}
})
</script>
推荐阅读
- html - 如何通过链接/api 加入新的 google 群组
- c# - 达到一定分数后统一退出游戏
- python - Python一一显示字母,其余为点,空格为空格
- typo3 - 在 TypoScript 中,如果满足 c1&c2&c3 条件,如何在菜单项旁边显示“新建”?
- scheduled-tasks - 在多个实例上访问 Quartz 中的计划作业
- linux - Bash 数组作为 kafka-topics 的参数
- html - 无法为引导 jumbotron 显示背景图像
- android - 在 Android Enterprise 专用设备上以编程方式重新启动 android
- python - Python3.5代码与两台机器上不同的输出相同
- vba - 配方更新 - 特定阶段的行选择