项目场景:
对于很多像笔者一样的新手前端开发者,在编写前端代码的时候,大多是边学边写的状态。在做一些个人的、非商业的项目时,我们也许会经常去到各类前端设计网站获取灵感和素材(e.g. https://codepen.io/)。然而在Vue架构下,素材网站的普通的js代码并不能像html一样简单粘贴,网上相关解决办法也比较少,笔者进行相关探索后总结经验如下。
问题描述
如何在Vue框架下使用普通html中的js代码:
解决方案:
首先我们要创建一个.vue文件来表示这个组件,把html和css写在这里
<template>
<div></div>
</template>
<script>
export default {
}
</script>
<style scoped>
</style>
找到vue项目中
public
文件夹下的index.html
,在<body></body>中添加标签<script id=“rendered-js” type=“module”><script>,把要使用的js代码粘贴到标签下就好了。
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<script id="rendered-js" type="module">
//TODO: Your js code
</script>
</body>
举个例子
假设我们想在项目中使用如下素材:https://codepen.io/jaredstanley/pen/qBKNNWg
我们先新建一个Test.vue,将html和css复制过去。
注意: 这个示例html代码中也有js代码,将一并归到js里,不在Test.vue中写
<template>
<div>
<canvas class="webgl"></canvas>
</div>
</template>
<script>
export default {
}
</script>
<style scoped>
.webgl
{
position: fixed;
top: 0;
left: 0;
outline: none;
}
</style>
然后找到
index.html
将js代码全部粘贴过去
<script id="rendered-js" type="module">
import * as THREE from "https://cdn.skypack.dev/three@0.146.0";
import { OrbitControls } from '//cdn.skypack.dev/three@0.125.0/examples/jsm/controls/OrbitControls.js?min'
import * as datGui from "https://cdn.skypack.dev/dat.gui@0.7.9";
//TODO: 左侧html框中的<script>部分
//TODO: 右侧js除import外剩余所有
</script>
运行
npm run serve
: