赞
踩
环境: node 12.18.3,npm 6.14.6 或 yarn 1.22.10
- npm init @vitejs/app my-first-vite-app --template vue
- 或
- yarn create @vitejs/app my-first-vite-app --template vue
- >cd my-first-vite-app
- >yarn
- >yarn dev
1. 环境变量
.env.development
- NODE_ENV=development
-
- VITE_APP_WEB_URL='https://cn.vitejs.dev/'
.env.production
- NODE_ENV=production
-
- 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
- import { createApp} from 'vue'
- import App from './App.vue'
-
- const app = createApp(App)
- //配置全局变量
- app.config.globalProperties.$http= (name) => `my name is ${name}`
- app.mount('#app')
App.vue
- <template>
- <HelloWorld :msg="msg" />
- <input type="text" v-model="info"/>
- <p>{{fullName}}</p>
- </template>
-
- <script>
- import HelloWorld from "./components/HelloWorld.vue"
- import {ref,getCurrentInstance,watchEffect,watch,computed} from 'vue'
- export default {
- components:{
- HelloWorld
- },
- setup() {
- const info = ref("欢迎光临")
- //getCurrentInstance 支持访问内部组件实例,只能在 setup 或生命周期钩子中调用。
- //如需在 setup 或生命周期钩子外使用,请先在 setup 中调用 getCurrentInstance()
- //获取该实例然后再使用。
- const { proxy } = getCurrentInstance()
- //打印全局变量
- console.log(proxy.$http('joy'))
- console.log(process.env.NODE_ENV) // console --> development
- console.log(import.meta.env.MODE) // console --> development
- console.log(import.meta.env.VITE_APP_WEB_URL) // console --> https://cn.vitejs.dev/
- // watchEffect
- watchEffect(() => {console.log(info.value)})
- //watch
- watch(info,(newval,oldval) =>{
- console.log(`我是旧值${oldval},我是新值${newval}`)
- })
- //computed
- const fullName = computed(() => `${info.value}美丽屋`)
-
- const msg = ref('Hello Vue 3 + Vite')
-
- return {msg,info,fullName }
- },
- }
- </script>
-
- <style>
- #app {
- font-family: Avenir, Helvetica, Arial, sans-serif;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- }
- </style>
vite.config.js
- import { defineConfig } from 'vite'
- import vue from '@vitejs/plugin-vue'
- import { resolve } from 'path';
-
- export default defineConfig({
- plugins: [vue()],
- resolve: {
- alias: {
- '@': resolve(__dirname, "src") //设置别名
- }
- },
- base: './',
- server: {
- host: 'localhost',
- port: 8086,
- open: true,
- },
- })
NPM
npm install vue-router@4 --save
yarn add vue-router@4 --save
main.js
- import { createApp} from 'vue'
- import App from './App.vue'
- import router from '@/router'
-
- const app = createApp(App)
- app.config.globalProperties.$http = (name) => `my name is ${name}`
- app.use(router)
- app.mount('#app')
在src下新建文件夹 router,在router下建立文件
index.js
- import {createRouter,createWebHistory} from 'vue-router';
- import routes from './routes'
-
- const router = createRouter({
- history:createWebHistory("/viteApp/"), //history模式使用HTML5模式
- routes,
- });
-
- export default router;
routes.js
- export default [
- {
- path: '/',
- name: 'home',
- component: () => import('@/views/home.vue'), //路由懒加载
- },
- {
- path: '/wxc',
- name: 'wxc',
- component: () => import('@/views/wxc.vue'), //路由懒加载
- },
- ];
home.vue
- <template>
- <div>{{msg}}</div>
- <div @click="gotoStore()">{{todo}}</div>
- </template>
-
- <script>
- import {ref,getCurrentInstance} from 'vue'
- import {onBeforeRouteLeave,useRouter} from 'vue-router';
- export default {
- setup(){
- const todo = ref('去万象城')
- const msg = ref('我是home页')
- const router = useRouter()
-
- const gotoStore = () => { router.push({name: 'wxc'})}
-
- //const { proxy } = getCurrentInstance();
- //const gotoStore = () => proxy.$router.push({ name: "wxc" });
-
- onBeforeRouteLeave(() =>{
- console.log('我离开了home')
- })
- return {msg,todo,gotoStore}
- }
- }
- </script>
- <style scoped>
- </style>
NPM
npm install vuex@next --save
Yarn
yarn add vuex@next --save
main.js
- import { createApp } from 'vue'
- import App from './App.vue'
- import router from '@/router'
- import { store } from '@/store'
-
- const app = createApp(App)
- app.config.globalProperties.$http = name => `my name is ${name}`
- app.use(router).use(store).mount('#app')
在src下新建文件夹 store,在store下建立文件
index.js
- import {createStore} from 'vuex'
- import {mutations} from './mutations'
- import {actions} from './actions'
-
- export const store = createStore({
- state:{
- typeId: 'user001',
- showName: true,
- count: 0,
- user:{
- name: 'joy',
- pwd: '123456'
- }
- },
- getters:{
- getId(state){
- return state.typeId
- },
- getUser(state){
- return state.user
- }
-
- },
- mutations,
- actions
- })
mutations.js
- export const mutations = {
- showUserName(state){
- state.showName = false
- },
- updateCount(state){
- state.count++
- }
- }
actions.js
- export const actions = {
- getUserList({commit}){
- commit('updateCount')
- }
- }
home.vue
- <template>
- <div>{{msg}}</div>
- <div @click="gotoStore()">{{todo}}</div>
- </template>
-
- <script>
- import {ref} from 'vue'
- import {onBeforeRouteLeave,useRouter} from 'vue-router';
- import {useStore} from 'vuex'
- export default {
- setup(){
- const todo = ref('去万象城')
- const msg = ref('我是home页')
- const router = useRouter()
- console.log(router)
-
- const gotoStore = () => { router.push({name: 'wxc'})}
- onBeforeRouteLeave(() =>{
- console.log('我离开了home')
- })
- const store = useStore();
- console.log(store)
- store.commit('showUserName')
- store.dispatch('getUserList')
- console.log(store.state.showName)
- console.log(store.state.count)
-
- return {msg,todo,gotoStore}
- }
- }
- </script>
- <style scoped>
- </style>
NPM
npm install sass -D
Yarn
yarn add sass -D
vite.config.js
- import {defineConfig} from 'vite'
- import vue from '@vitejs/plugin-vue'
- import styleImport from 'vite-plugin-style-import'
- import { resolve } from 'path';
-
- export default defineConfig({
- plugins: [vue()],
- resolve: {
- alias: {
- '@': resolve(__dirname, "src")
- }
- },
- base: './',
- server: {
- host: '10.0.13.63',
- port: 8086,
- open: true,
- },
- css:{
- preprocessorOptions: {
- scss: {
- additionalData: `@import "./src/assets/common/common.scss";`//引用公共样式,使用vite搭建项目只安装sass即可,不需要安装node-sass,sass-loader
- }
- }
- }
- });
-
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
- import { defineConfig } from 'vite'
- import vue from '@vitejs/plugin-vue'
- import { resolve } from 'path';
- import styleImport from 'vite-plugin-style-import'
-
- export default defineConfig({
- plugins: [vue(),
- styleImport({
- libs: [{
- libraryName: 'vant',
- esModule: true,
- resolveStyle: (name) => {
- return `vant/es/${name}/style/index`;
- }
- }]
- })
- ],
- resolve: {
- alias: {
- '@': resolve(__dirname, "src") //设置别名
- }
- },
- base: './',
- server: {
- host: 'localhost',
- port: 8086,
- open: true,
- },
- css:{
- preprocessorOptions: {
- scss: {
- additionalData: `@import "./src/assets/common/common.scss";`//引用公共样式,使用vite搭建项目只安装sass即可,不需要安装node-sass,sass-loader
- }
- }
- }
- })
main.js
- import { createApp } from 'vue'
- import App from './App.vue'
- import router from '@/router'
- import { store } from '@/store'
- import { NavBar } from 'vant';
- import { Icon } from 'vant';
- import { Swipe, SwipeItem } from 'vant';
- import { NoticeBar } from 'vant';
- import { Card } from 'vant';
- const app = createApp(App)
- app.config.globalProperties.$http = name => `my name is ${name}`
- app.use(router).use(store).use(Icon).use(NavBar).use(Swipe).use(SwipeItem).use(NoticeBar).use(Card).mount('#app')
wxc.vue
- <template>
- <div class="main-box">
- <van-nav-bar
- title="万象城"
- left-text="返回"
- right-text="反馈"
- left-arrow
- @click-left="onClickLeft"
- @click-right="onClickRight"
- />
- <van-notice-bar
- left-icon="volume-o"
- text="在代码阅读过程中人们说脏话的频率是衡量代码质量的唯一标准。"
- />
- <van-swipe
- class="my-swipe"
- :autoplay="3000"
- lazy-render
- :height="240"
- @change="onChange"
- >
- <van-swipe-item v-for="image in images" :key="image">
- <img :src="image" />
- </van-swipe-item>
- <template #indicator>
- <div class="custom-indicator">
- {{ current + 1 }}/{{ images.length }}
- </div>
- </template>
- </van-swipe>
- <van-card
- v-for="i in 3"
- :key="i"
- num="2"
- price="2.00"
- desc="描述信息"
- title="商品标题"
- thumb="https://img.yzcdn.cn/vant/ipad.jpeg"
- />
- </div>
- </template>
-
- <script>
- import { ref, reactive } from "vue"
- import { useRouter } from "vue-router"
- export default {
- props: ["name"],
- setup(props) {
- console.log(props)
-
- const router = useRouter()
- const onClickLeft = () => router.push({ name: "home" })
- const onClickRight = () => ""
- const images = [
- "https://img.yzcdn.cn/vant/apple-1.jpg",
- "https://img.yzcdn.cn/vant/apple-2.jpg",
- ]
- const current = ref(0)
- const onChange = (index) => {
- current.value = index
- }
- return { onClickLeft, onClickRight, images, current, onChange }
- },
- created() {
- console.log("config", this.$http("lily"))
- },
- }
- </script>
- <style lang="scss" scoped>
- .main-box {
- width: 100vw;
- height: 100vh;
- }
- img {
- width: 100vw;
- height: 240px;
- }
- .custom-indicator {
- position: absolute;
- right: 5px;
- bottom: 5px;
- padding: 2px 5px;
- font-size: 12px;
- background: rgba(0, 0, 0, 0.1);
- }
- .my-swipe .van-swipe-item {
- padding-top: 1px;
- }
- </style>
完工
搭建过程中错用了vite1中的一些设置,导致浪费了好多脑细胞,总之要认真看官方文档,别搞错版本就行,vite 速度真的很快,后续现在小的生产项目上试试手。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。