Vue3+Vite学习

1. 文档地址

2. 创建项目方式

npm init @vitejs/app
npm init @vitejs/app my-vue-app -- --template vue

##3. 配置文件

4. setup 的语法糖

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Hello Vue 3 + Vite" />
  <Message @myclick="clickMe" msg="message from app" ref="hw" />
  <Comp />
</template>

<script setup>
import HelloWorld from '@/components/HelloWorld.vue'
import Message from '@/components/Message.vue'
import Comp from '@/components/Comp.vue'
import { ref } from 'vue'

const hw = ref(null)

const clickMe = (options) => {
  console.log('我是来自 Message 组件的 Emit 触发的事件,参数是:', options)
  hw.value.someMethod()
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

5. 获取上下文

// 获取上下文
const ctx = useContext()
ctx.expose({
  someMethod() {
    console.log('expose methods from Message.')
  }
})

6. 自定义事件

// 定义事件
const emit = defineEmit(['myclick'])
const myclick = () => {
  // emit('myclick', { type: 'click', message: 'this is message.' })
  ctx.emit('myclick', { type: 'click', message: 'this is message.' })
}

7. 使用 JSX 语法

  • 安装插件

    • npm i @vitejs/plugin-vue-jsx
  • vite.config.js 引用插件

    import vueJsx from '@vitejs/plugin-vue-jsx'
    
    export default defineConfig({
      plugins: [vueJsx()]
    })
    
  • 使用

    export default {
      setup() {
        const counter = ref(0)
        const onclick = () => {
          counter.value++
        }
        return () => (
          <>
            <div>comp</div>
            <p onClick={onclick}>{counter.value}</p>
          </>
        )
      }
    }
    

8. 使用 Mock 数据

  • 安装插件

    npm i mockjs -S
    
    npm i vite-plugin-mock cross-env -D
    
  • 更改 package.json文件

    {
      "scripts": {
        "dev": "cross-env NODE_ENV=development vite"
      }
    }
    
  • 引入插件

    import viteMockServe from 'vite-plugin-mock'
    
    export default defineConfig({
      plugins: [viteMockServe({ supportTs: false })]
    })
    
  • 在根目录创建一个 mock 目录,并创建一个 user.js 文件,写入以下数据

    export default {
      url: '/api/getUsers',
      method: 'get',
      response: () => {
        return {
          code: 0,
          message: 'ok',
          data: ['tom', 'jerry']
        }
      }
    }
    
  • 在项目中使用

    fetch('/api/getUsers').then(res => res.json()).then(response => console.log(response))
    

9. Router 的使用

  • 安装插件

    npm i vue-router@next -S
    
  • 创建 src/router/index.js,写入以下内容

    import { createRouter, createWebHashHistory } from 'vue-router'
    
    const router = createRouter({
      history: createWebHashHisotry(),
      routes: [
        { path: '/', component: () => import('@/views/home.vue') } // 文件不存在请创建
      ]
    })
    
    export default router
    
  • main.js 文件中引入刚刚的文件

    import router from './router'
    
    createApp(App).use(router).mount('#app')
    

10. Vuex 的使用

  • 安装插件

    npm i vuex@next -S
    
  • 创建 src/store/index.js ,写入以下内容

    import { createStore } from 'vuex'
    
    export default createStroe({
      state: {
        counter: 100
      },
      mutations: {
        add(state, payload) {
          state.counter++
        }
      }
    })
    
  • main.js 中使用

    import store from './store'
    
    createApp(App).use(router).use(store).mount('#app')
    

11. SCSS 的使用

  • 安装

    npm i sass -D
    
  • 创建样式文件 styles/index.scss,写入以下文件

    @mixin clearfix {
      &::after {
        content: '';
        display: table;
        clear: both;
      }
    }
    
    @mixin scrollBar {
      &::-webkit-scrollbar-track-piece {
        background-color: #d3dce6;
      }
    
      &::-webkit-scrollbar {
        width: 6px;
      }
    
      &::-webkit-scrollbar-thumb {
        background-color: #99a9bf;
        border-radius: 20px;
      }
    }
    
  • main.js 中引入全局样式

    import './styles/index.scss'
    

12. 集成 Element3

  • 安装

    npm i element3 -S
    
  • main.js 中引入

    import element3 from 'element3'
    import 'element3/lib/theme-chalk/index.css'
    
    // use 一下
    createApp(App).use(element3).mount('#app')
    
  • 另外一种方式,创建 plugins/element3.js 文件,写入以下内容

    import element3 from 'element3'
    import 'element3/lib/theme-chalk/index.css'
    
    export default function(app) {
      app.use(element3)
    }
    
    // 在 main.js 中引入
    import element3 './plugins/element3.js'
    createApp(App).use(element3).mount('#app')
    

13. 配合 github 自动部署

  • 项目根目录创建 .github/workflows/publish.yaml 文件,写入以下内容

    # 给工作流设置名字
    name: 打包应用并上传
    on:
    	# 工作流监听的事件
      push:
      	# 监听的分支列表
        branches:
          - master
    
    # 工作流
    jobs:
      build:
         # runs-on 指定 job 任务运行所需要的虚拟机环境
        runs-on: ubuntu-latest
        steps:
          # 获取源码
          - name: 迁出代码
            uses: actions/checkout@master
    
          # 安装 node10
          - name: 安装 node.js
            uses: actions/setup-node@v1
            with:
              node-version: 14.0.0
    
          # 安装依赖
          - name: 安装依赖
            run: npm install
    
          # 打包
          - name: 打包
            run: npm run build
            
          # 上传 阿里云
          - name: 发布到阿里云
            uses: easingthemes/ssh-deploy@v2.1.5
            env:
              # 私钥
              SSH_PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
              # scp 参数
              ARGS: "-avzr --delete"
              # 源目录
              SOURCE: "dist"
              # 服务器 IP 地址
              REMOTE_HOST: "47.93.230.33"
              # 用户
              REMOTE_USER: "root"
              # 目标地址
              TARGET: "/www/wwwroot/vue-in-action"
    
  • 创建 RSA 证书免密登陆

    • 输入以下命令创建

      ssh-keygen -m PEM -t rsa -b 4096
      
    • 找到刚刚创建的 ~/.ssh/id_rsa.pub 文件,复制到服务器的 ~/.ssh/authorized_keys 文件中,实现免密登陆

  • github 指定的项目 settings/Secrets 中添加一个名为 PRIVATE_KEY 的变量,值为刚刚创建的 ~/.ssh/id_rsa 的内容

  • 执行以上步骤之后,每次 push 代码到 master 分支的时候都会执行 build 这个任务


版权声明:本文为xfjpeter原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。