当前位置:   article > 正文

使用vite2 快速搭建 vue3 项目 ( router + vuex + scss + vant )_vite vant additionaldata

vite vant additionaldata

 

文章目录

 


前言

环境: node 12.18.3,npm 6.14.6 或 yarn 1.22.10

 

一、使用vite创建项目

  1.  npm init @vitejs/app my-first-vite-app --template vue
  2. yarn create @vitejs/app my-first-vite-app --template vue
  3. >cd my-first-vite-app
  4. >yarn
  5. >yarn dev

  到这里项目就搭建好了,下面开始配置文件

1. 环境变量

.env.development

  1. NODE_ENV=development
  2. VITE_APP_WEB_URL='https://cn.vitejs.dev/'

.env.production

  1. NODE_ENV=production
  2.   
  3. VITE_APP_WEB_URL= 'https://baidu.com'

 

2.定义全局变量

vue2 : Vue.prototype.$http = (name) => `my name is ${name}`

 使用:this.$http();

vue3 : app.config.globalProperties.$http= (name) => `my name is ${name}`

 使用: this.$http();  如果在 setup 函数中,因为this是 undefined,所以需要通过getCurrentInstance函数来使用

3. watchEffect,watch, computed的使用见下图,watchEffect,watch区别在于watchEffect不获取旧值

main.js

  1. import { createApp} from 'vue'
  2. import App from './App.vue'
  3. const app = createApp(App)
  4. //配置全局变量
  5. app.config.globalProperties.$http= (name) => `my name is ${name}`
  6. app.mount('#app')

App.vue

  1. <template>
  2. <HelloWorld :msg="msg" />
  3. <input type="text" v-model="info"/>
  4. <p>{{fullName}}</p>
  5. </template>
  6. <script>
  7. import HelloWorld from "./components/HelloWorld.vue"
  8. import {ref,getCurrentInstance,watchEffect,watch,computed} from 'vue'
  9. export default {
  10. components:{
  11. HelloWorld
  12. },
  13. setup() {
  14. const info = ref("欢迎光临")
  15. //getCurrentInstance 支持访问内部组件实例,只能在 setup 或生命周期钩子中调用。
  16. //如需在 setup 或生命周期钩子外使用,请先在 setup 中调用 getCurrentInstance()
  17. //获取该实例然后再使用。
  18. const { proxy } = getCurrentInstance()
  19. //打印全局变量
  20. console.log(proxy.$http('joy'))
  21. console.log(process.env.NODE_ENV) // console --> development
  22. console.log(import.meta.env.MODE) // console --> development
  23. console.log(import.meta.env.VITE_APP_WEB_URL) // console --> https://cn.vitejs.dev/
  24. // watchEffect
  25. watchEffect(() => {console.log(info.value)})
  26. //watch
  27. watch(info,(newval,oldval) =>{
  28. console.log(`我是旧值${oldval},我是新值${newval}`)
  29. })
  30. //computed
  31. const fullName = computed(() => `${info.value}美丽屋`)
  32. const msg = ref('Hello Vue 3 + Vite')
  33. return {msg,info,fullName }
  34. },
  35. }
  36. </script>
  37. <style>
  38. #app {
  39. font-family: Avenir, Helvetica, Arial, sans-serif;
  40. -webkit-font-smoothing: antialiased;
  41. -moz-osx-font-smoothing: grayscale;
  42. }
  43. </style>

vite.config.js

  1. import { defineConfig } from 'vite'
  2. import vue from '@vitejs/plugin-vue'
  3. import { resolve } from 'path';
  4. export default defineConfig({
  5. plugins: [vue()],
  6. resolve: {
  7. alias: {
  8. '@': resolve(__dirname, "src") //设置别名
  9. }
  10. },
  11. base: './',
  12. server: {
  13. host: 'localhost',
  14. port: 8086,
  15. open: true,
  16. },
  17. })

二、引入router

NPM

npm install vue-router@4  --save

Yarn

yarn add vue-router@4 --save

main.js

  1. import { createApp} from 'vue'
  2. import App from './App.vue'
  3. import router from '@/router'
  4. const app = createApp(App)
  5. app.config.globalProperties.$http = (name) => `my name is ${name}`
  6. app.use(router)
  7. app.mount('#app')

在src下新建文件夹 router,在router下建立文件

index.js

  1. import {createRouter,createWebHistory} from 'vue-router';
  2. import routes from './routes'
  3. const router = createRouter({
  4. history:createWebHistory("/viteApp/"), //history模式使用HTML5模式
  5. routes,
  6. });
  7. export default router;

 routes.js

  1. export default [
  2. {
  3. path: '/',
  4. name: 'home',
  5. component: () => import('@/views/home.vue'), //路由懒加载
  6. },
  7. {
  8. path: '/wxc',
  9. name: 'wxc',
  10. component: () => import('@/views/wxc.vue'), //路由懒加载
  11. },
  12. ];

home.vue

  1. <template>
  2. <div>{{msg}}</div>
  3. <div @click="gotoStore()">{{todo}}</div>
  4. </template>
  5. <script>
  6. import {ref,getCurrentInstance} from 'vue'
  7. import {onBeforeRouteLeave,useRouter} from 'vue-router';
  8. export default {
  9. setup(){
  10. const todo = ref('去万象城')
  11. const msg = ref('我是home页')
  12. const router = useRouter()
  13. const gotoStore = () => { router.push({name: 'wxc'})}
  14. //const { proxy } = getCurrentInstance();
  15. //const gotoStore = () => proxy.$router.push({ name: "wxc" });
  16. onBeforeRouteLeave(() =>{
  17. console.log('我离开了home')
  18. })
  19. return {msg,todo,gotoStore}
  20. }
  21. }
  22. </script>
  23. <style scoped>
  24. </style>

三、引入vuex

NPM

npm install vuex@next --save

Yarn

yarn add vuex@next --save

main.js

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import router from '@/router'
  4. import { store } from '@/store'
  5. const app = createApp(App)
  6. app.config.globalProperties.$http = name => `my name is ${name}`
  7. app.use(router).use(store).mount('#app')

在src下新建文件夹 store,在store下建立文件

index.js

  1. import {createStore} from 'vuex'
  2. import {mutations} from './mutations'
  3. import {actions} from './actions'
  4. export const store = createStore({
  5. state:{
  6. typeId: 'user001',
  7. showName: true,
  8. count: 0,
  9. user:{
  10. name: 'joy',
  11. pwd: '123456'
  12. }
  13. },
  14. getters:{
  15. getId(state){
  16. return state.typeId
  17. },
  18. getUser(state){
  19. return state.user
  20. }
  21. },
  22. mutations,
  23. actions
  24. })

mutations.js

  1. export const mutations = {
  2. showUserName(state){
  3. state.showName = false
  4. },
  5. updateCount(state){
  6. state.count++
  7. }
  8. }

actions.js

  1. export const actions = {
  2. getUserList({commit}){
  3. commit('updateCount')
  4. }
  5. }

home.vue

  1. <template>
  2. <div>{{msg}}</div>
  3. <div @click="gotoStore()">{{todo}}</div>
  4. </template>
  5. <script>
  6. import {ref} from 'vue'
  7. import {onBeforeRouteLeave,useRouter} from 'vue-router';
  8. import {useStore} from 'vuex'
  9. export default {
  10. setup(){
  11. const todo = ref('去万象城')
  12. const msg = ref('我是home页')
  13. const router = useRouter()
  14. console.log(router)
  15. const gotoStore = () => { router.push({name: 'wxc'})}
  16. onBeforeRouteLeave(() =>{
  17. console.log('我离开了home')
  18. })
  19. const store = useStore();
  20. console.log(store)
  21. store.commit('showUserName')
  22. store.dispatch('getUserList')
  23. console.log(store.state.showName)
  24. console.log(store.state.count)
  25. return {msg,todo,gotoStore}
  26. }
  27. }
  28. </script>
  29. <style scoped>
  30. </style>

四、引入 scss

NPM

npm  install sass -D

Yarn 

yarn add sass -D

vite.config.js

  1. import {defineConfig} from 'vite'
  2. import vue from '@vitejs/plugin-vue'
  3. import styleImport from 'vite-plugin-style-import'
  4. import { resolve } from 'path';
  5. export default defineConfig({
  6. plugins: [vue()],
  7. resolve: {
  8. alias: {
  9. '@': resolve(__dirname, "src")
  10. }
  11. },
  12. base: './',
  13. server: {
  14. host: '10.0.13.63',
  15. port: 8086,
  16. open: true,
  17. },
  18. css:{
  19. preprocessorOptions: {
  20. scss: {
  21. additionalData: `@import "./src/assets/common/common.scss";`//引用公共样式,使用vite搭建项目只安装sass即可,不需要安装node-sass,sass-loader
  22. }
  23. }
  24. }
  25. });

五、引入vant 

NPM 

npm i vant@next -S

Yarn

yarn add vant@next -S

配置按需引入,需要先安装插件,可以使用 vite-plugin-style-import 或 vite-plugin-imp 实现按需引入,本文使用 vite-plugin-style-import 

npm i vite-plugin-style-import -D
yarn add vite-plugin-style-import -D

vite.config.js

  1. import { defineConfig } from 'vite'
  2. import vue from '@vitejs/plugin-vue'
  3. import { resolve } from 'path';
  4. import styleImport from 'vite-plugin-style-import'
  5. export default defineConfig({
  6. plugins: [vue(),
  7. styleImport({
  8. libs: [{
  9. libraryName: 'vant',
  10. esModule: true,
  11. resolveStyle: (name) => {
  12. return `vant/es/${name}/style/index`;
  13. }
  14. }]
  15. })
  16. ],
  17. resolve: {
  18. alias: {
  19. '@': resolve(__dirname, "src") //设置别名
  20. }
  21. },
  22. base: './',
  23. server: {
  24. host: 'localhost',
  25. port: 8086,
  26. open: true,
  27. },
  28. css:{
  29. preprocessorOptions: {
  30. scss: {
  31. additionalData: `@import "./src/assets/common/common.scss";`//引用公共样式,使用vite搭建项目只安装sass即可,不需要安装node-sass,sass-loader
  32. }
  33. }
  34. }
  35. })

main.js

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import router from '@/router'
  4. import { store } from '@/store'
  5. import { NavBar } from 'vant';
  6. import { Icon } from 'vant';
  7. import { Swipe, SwipeItem } from 'vant';
  8. import { NoticeBar } from 'vant';
  9. import { Card } from 'vant';
  10. const app = createApp(App)
  11. app.config.globalProperties.$http = name => `my name is ${name}`
  12. app.use(router).use(store).use(Icon).use(NavBar).use(Swipe).use(SwipeItem).use(NoticeBar).use(Card).mount('#app')

wxc.vue

  1. <template>
  2. <div class="main-box">
  3. <van-nav-bar
  4. title="万象城"
  5. left-text="返回"
  6. right-text="反馈"
  7. left-arrow
  8. @click-left="onClickLeft"
  9. @click-right="onClickRight"
  10. />
  11. <van-notice-bar
  12. left-icon="volume-o"
  13. text="在代码阅读过程中人们说脏话的频率是衡量代码质量的唯一标准。"
  14. />
  15. <van-swipe
  16. class="my-swipe"
  17. :autoplay="3000"
  18. lazy-render
  19. :height="240"
  20. @change="onChange"
  21. >
  22. <van-swipe-item v-for="image in images" :key="image">
  23. <img :src="image" />
  24. </van-swipe-item>
  25. <template #indicator>
  26. <div class="custom-indicator">
  27. {{ current + 1 }}/{{ images.length }}
  28. </div>
  29. </template>
  30. </van-swipe>
  31. <van-card
  32. v-for="i in 3"
  33. :key="i"
  34. num="2"
  35. price="2.00"
  36. desc="描述信息"
  37. title="商品标题"
  38. thumb="https://img.yzcdn.cn/vant/ipad.jpeg"
  39. />
  40. </div>
  41. </template>
  42. <script>
  43. import { ref, reactive } from "vue"
  44. import { useRouter } from "vue-router"
  45. export default {
  46. props: ["name"],
  47. setup(props) {
  48. console.log(props)
  49. const router = useRouter()
  50. const onClickLeft = () => router.push({ name: "home" })
  51. const onClickRight = () => ""
  52. const images = [
  53. "https://img.yzcdn.cn/vant/apple-1.jpg",
  54. "https://img.yzcdn.cn/vant/apple-2.jpg",
  55. ]
  56. const current = ref(0)
  57. const onChange = (index) => {
  58. current.value = index
  59. }
  60. return { onClickLeft, onClickRight, images, current, onChange }
  61. },
  62. created() {
  63. console.log("config", this.$http("lily"))
  64. },
  65. }
  66. </script>
  67. <style lang="scss" scoped>
  68. .main-box {
  69. width: 100vw;
  70. height: 100vh;
  71. }
  72. img {
  73. width: 100vw;
  74. height: 240px;
  75. }
  76. .custom-indicator {
  77. position: absolute;
  78. right: 5px;
  79. bottom: 5px;
  80. padding: 2px 5px;
  81. font-size: 12px;
  82. background: rgba(0, 0, 0, 0.1);
  83. }
  84. .my-swipe .van-swipe-item {
  85. padding-top: 1px;
  86. }
  87. </style>

完工


总结

    搭建过程中错用了vite1中的一些设置,导致浪费了好多脑细胞,总之要认真看官方文档,别搞错版本就行,vite 速度真的很快,后续现在小的生产项目上试试手。

   

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/392347
推荐阅读
相关标签
  

闽ICP备14008679号