Vue3 入门教程

(一) 创建项目

  1. 安装脚手架

    npm install -g create-vite-app
    
  2. 创建项目

    create-vite-app projectName
    
  3. 安装依赖

    用vscode打开项目, 运行 npm i

  4. 运行项目

    npm run dev // 可以在package.json里修改
    
  5. 预览项目

    用浏览器打开: http://localhost:3000

  6. vscode安装vue3插件 Volar

(二) 路由配置

  1. 安装依赖

    npm i vue-router
    
  2. 创建product, my, login, demo组件

  3. 创建路由

    src/router/index.js

    import { createRouter, createWebHistory } from "vue-router";
    
    const routes = [
      {
        path: "/",
        redirect: "/product/list",
      },
      {
        path: "/product",
        component: () => import("../views/product/index.vue"),
        children: [
          {
            path: "list",
            component: () => import("../views/product/list.vue"),
          },
          {
            path: "detail",
            component: () => import("../views/product/detail.vue"),
          },
        ],
      },
      {
        path: "/my",
        component: () => import("../views/my/index.vue"),
      },
      {
        path: "/login",
        component: () => import("../views/login/index.vue"),
      },
      {
        path: "/demo",
        component: () => import("../views/demo/index.vue"),
      },
    ];
    
    const router = createRouter({ 
      history: createWebHistory(),
      routes,  
    });
    
    export default router;
    
    
  4. 使用路由

    main.js

    import { createApp } from "vue";
    import App from "./App.vue";
    import "./index.css";
    import router from "./router/index";
    
    const app = createApp(App);
    app.use(router);
    app.mount("#app");
    
  5. 配置路由出口

    App.vue

    <template>
        <router-view></router-view> 
    </template>
    
    <script>  
    export default {
      name: 'App', 
    }
    </script>
    

(三) options api和composition api

  1. vue2使用选项式 api(options api)

  2. vue3使用组合式 api(composition api)

(1) vue2项目

<template>
  <div>demo</div>
</template>

<script>
export default {
  data() {
    return {};
  },

  create() {},
  filter: {},
  computed: {},
};
</script>

(2) vue3项目

// 写法1
<template>
  <div>
      {{add()}}
  </div>
</template>

<script>
export default {
    setup() {
        const add = () => {
            return 222;
        }    

        return {
            add
        }
    }
};
</script>

// 写法2
<template>
  <div>{{msg}}</div>
</template>

<script setup>
import { ref } from "vue";
import {useRouter} from 'vue-router';
let msg = ref("hello");
const router = useRouter();
router.push('/my');
</script>

(四) 创建响应式数据(ref)

<template>
  <div> 
      {{ count }}
      </div>
</template>

<script setup>
import { ref } from "vue";
let msg = ref("");
let count = ref(0);
let arr = ref([1,2,3])

// 修改变量的值
setTimeout(()=> {
    count.value = 100;
},2000) 
</script>

(五) 父子组件通信

(六) 路由跳转和传参

(七) 创建响应式数据(reactive)

(八) 跨组件通信(pinia)

参考地址

(1) Pinia 简介与基础

1.1 Pinia 简介

官方地址:https://pinia.vuejs.org/ Pinia 是 Vuex4 的升级版,也就是 Vuex5 Pinia 极大的简化了Vuex的使用,是 Vue3的新的状态管理工具 Pinia 对 ts的支持更好,性能更优, 体积更小,无 mutations,可用于 Vue2 和 Vue3 Pinia支持Vue Devtools、 模块热更新和服务端渲染

1.2 Pinia 基础

Vuex 与 Pinia 对比

Vuex 中核心部分: State、Getters、Mutations(同步) 和 Actions(异步) Pinia 中核心部分: State、Getters 和 Actions(同步异步均支持)

Pinia 各部分作用

State: 类似于组件中data,用于存储全局状态 Getters: 类似于组件中的computed,根据已有的State封装派生数据,也具有缓存的特性 Actions: 类似于组件中的methods,用于封装业务逻辑,同步异步均可以

(2) Pinia基础使用流程

1. 安装 pinia

npm install pinia -S

package.json文件中

 "dependencies": {
    "pinia": "^2.0.9",
    "vue": "^3.2.25"
  },

2. 创建 pinia 实例并挂载到 vue中

// main.ts 文件
import { createApp } from 'vue'
import App from './App.vue'
// 导入和创建 Pinia 实例
import {createPinia} from 'pinia'
const pinia = createPinia() 
const app = createApp(App)
// 挂载到 Vue 根实例
app.use(pinia)
app.mount('#app') 

3. 在src文件下创建一个store文件夹,并添加index.ts

// store/index.ts
import { defineStore } from 'pinia' 
export const useMainStore =  defineStore('main',{
    state:()=>{
        return {
            info:"pinia 可以使用"
        }
    },
    getters:{},
    actions:{}
}) 

4. 在组件中使用

<template>
  <h1>{{ mainStore.info}}</h1>
</template>

<script lang="ts" setup>
import { useMainStore } from "../store";
const mainStore = useMainStore();
</script> 

(3) 进阶使用

1. state中数据的解构访问

状态管理中

state:()=>{
    return {
        info:"pinia 可以使用",
        count:10
    }
}, 

组件中

<template>
  <h1>{{ mainStore.count }}</h1>
  <h1>{{ mainStore.info }}</h1>
  <hr />
  <h1>{{ count }}</h1>
  <h1>{{ info }}</h1>
  <p>
    <button @click="alertData">修改数据</button>
  </p>
</template>

<script lang="ts" setup>
import { toRefs } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore } from "../store";
const mainStore = useMainStore();
const { count, info } = storeToRefs(mainStore);
const alertData = () => {
  mainStore.count += 10
}
</script> 

2. 修改state中的状态(数据)

// 一般的修改
const alertData = () => {
  mainStore.$patch(state => {
    state.count += 10
    state.info = "pinia批量更新"
  })
} 
// 通过actions修改
actions:{
  changeState (){
    this.count += 10
    this.info = "actions修改数据"
  },
    changeStates (num:number){
      this.count += num + 2
      this.info = "actions修改数据"
    }
} 
// 使用
const alertData = () => {
  mainStore.changeState()
  mainStore.changeStates(10)
} 

3. getters 的使用

定义

// 类似于组件的computed,用来封装计算属性,具有缓存的功能
getters:{
  // 函数接收一个可选参数:state状态对象
  count10(state){
    return state.count += 10
  },
    count10(state){
      return this.count += 10
    },
      // 若使用this.count,则必须指明返回数据的类型
      count11():number{
        return this.count += 11
      }
}, 

使用

<h1>{{ mainStore.count10 }}</h1>

(3) Pinia数据持久化

1. 手动保存至localStorage中

import { defineStore } from 'pinia';
const useLoginStore = defineStore({
  id: 'login',
  state: () => ({
    info: 'pinia 可以使用',
  }),
  getters: {},
  actions: {
    alertInfo() {
      this.info = '可以可以,这个秒';
    },
  },
});

// 数据持久化
// 1. 保存数据
const instance = useLoginStore();
instance.$subscribe((_, state) => {
  localStorage.setItem('login-store', JSON.stringify({ ...state }));
});
// 2. 获取保存的数据,先判断有无,无则用先前的
const old = localStorage.getItem('login-store');
if (old) {
  instance.$state = JSON.parse(old);
}
export default useLoginStore; 

使用 插件 pinia-plugin-persist 可以辅助实现数据持久化功能

2. 使用插件来实现

  1. 安装插件
pnpm install pinia-plugin-persist --save
  1. 修改main.js
import { createPinia } from 'pinia';
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import piniaPluginPersist from 'pinia-plugin-persist';
const pinia = createPinia();
pinia.use(piniaPluginPersist);
const app = createApp(App);
app.use(router);
app.use(pinia);
app.mount('#app');
  1. 配置要缓存的模块
import { defineStore } from 'pinia';
import piniaPluginPersist from 'pinia-plugin-persist';
const useLoginStore = defineStore({
  id: 'login',
  state: () => ({
    info: 'pinia 可以使用',
  }),
  // 开启数据缓存
  persist: {
    enabled: true,
  },
  getters: {},
  actions: {
    alertInfo() {
      this.info = '可以可以,这个秒';
    },
  },
});
export default useLoginStore;

其它设置,自定义保存名称,保存位置和需要保存的数据

// 开启数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        // 自定义名称
        key: 'login_store',
        // 保存位置,默认保存在sessionStorage
        storage: localStorage,
        // 指定要持久化的数据,默认所有 state 都会进行缓存,你可以通过 paths 指定要持久化的字段,其他的则不会进行持久化。
        paths: ['age'],
      },
    ],
  }, 

(九) 配置短路径

  1. 在根目录创建 vite.config.js

  2. 安装依赖

    npm i @vitejs/plugin-vue 或不行就添加--force  (强行安装)
    

    若vite是1.x版本, 要升级

    npm i vite@2
    
  3. vite.config.js的配置

    import {defineConfig} from 'vite'
    import vue from '@vitejs/plugin-vue'
    import path from 'path' 
    export default defineConfig({
        plugins: [vue()],
        resolve: {
            alias: {
                '@': path.resolve(__dirname, './src'),
                '@c': path.resolve(__dirname, './src/components'),
            },
        }
    })
    
  4. 使用

    <img src="../../assets/img/banner1.webp" alt="">
    <img src="@/assets/img/banner1.webp" alt="">