首页 > 解决方案 > 如何在 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>

标签: javascriptvue.js

解决方案


您试图在渲染之前获取元素。您的自定义脚本在其导入时执行,但在页面中呈现元素之前。您可以使用 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>

推荐阅读