平常再做开发的时候,一般情况下不会将html,js,css代码写到一个文件中。
基本上都会写在各自对应的文件中,然后再引入即可。
那么在VUE中我们如何抽离vue文件中的js,与css代码呢?
1:抽离javascript
Home.vue
1<template> 2 <div> 3 <div :style="{ padding: '24px', background: '#fff', minHeight: '360px' }"> 4 <h1>This is a home page</h1> 5 <HelloWorld msg="Hello Vue 3.0 + Vite" /> 6 </div> 7 </div> 8</template> 9 10<script lang="ts"> 11import { defineComponent } from "vue"; 12 13// 引入js文件 14import home from '/@/assets/js/admin/home'; 15// 使用js对象 16export default defineComponent({ 17 ...home, 18}); 19</script>
Home.ts
1import { defineComponent } from "vue"; 2import HelloWorld from "/@/components/HelloWorld.vue"; 3export default defineComponent({ 4 name: "Home", 5 components: { 6 HelloWorld, 7 }, 8});
2:抽离css
Admin.vue
1<template> 2 <div id=”app”> 3 <h1>This is a setting page</h1> 4 <p>store count is: {{ count }}</p> 5 </div> 6</template> 7<style lang="scss" scoped> 8 @import "../../assets/css/components/pc/Admin.scss"; 9</style> 10Admin.scss 11 12#app { 13 font-family: "Microsoft YaHei,微软雅黑,Arial,sans-serif,Helvetica Neue,Helvetica,Pingfang SC,Hiragino Sans GB"; 14 15 .ant-layout-sider { 16 .ant-layout-sider-children .ant-row-flex { 17 border-bottom: 1px solid rgb(240, 240, 240); 18 } 19 .ant-layout-sider-trigger { 20 border-top: 1px solid rgb(240, 240, 240); 21 } 22 } 23}
看到这里,你可能有疑问,为什么我能能在script标签中使用import标签引入scss呢?
具体请参照《Vite对TypeScript、CSS和JSON的支持》
以上就是抽离css,及js代码的示例。
有好的建议,请在下方输入你的评论。
欢迎访问个人博客
https://guanchao.site
本文转自 https://www.jianshu.com/p/2101e84a7faf,如有侵权,请联系删除。
