Vue3+Vite+Pinia 项目的搭建以及常用方法介绍

一.项目基础构建

1.vite构建vue

npm init vite@latest

2.src下创建router文件夹,router文件夹创建index.js文件

import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue";

const routes = [
    {
        path: "/",
        name: "Home",
        component: Home,
    },
    {
        path: "/about",
        name: "About",
        component: () =>
            import(/* webpackChunkName: "about" */ "../views/About.vue"),
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

export default router;

2.src下创建views文件夹,views文件夹创建About.vue、Home.vue两个路由文件

3.安装插件AutoImport(自动导入 Vue 相关函数,如:ref, reactive, toRef 等),并设置可以让@来代替src使用。

npm i unplugin-auto-import -D

vite.config.js写法如下

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from "unplugin-auto-import/vite"; //自动导入 Vue 相关函数,如:ref, reactive, toRef 等
import { resolve } from 'path';

export default defineConfig({
  plugins: [
    vue(),
    AutoImport({
      imports: ['vue', 'vue-router']
    })
  ],
  define: {
    'process.env': {},
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, './src'),
    },
  },
});

二.常用方法介绍

ref:响应式数据,在使用时候需要:str.value

let str = reactive('1');

 reactive:响应式数据,不需要.value,只能写对象或者数组

let str = reactive(['a','b','c']);

toRefs:结构响应式数据

let obj = reactive({
    name: '张三',
    age: 20
})

let { name, age } = toRefs(obj)

const btn = () => {
    name.value = '李四'
}

computed:计算属性

// 第1种写法
let changeStr = computed(() => {
    return str.value;
})

// 第2种写法
let changeStr2 = computed({
    get() {
        return str.value;
    },
    set(val) {
        str.value = val
    }
})

watch:监听事件

// (1)监听第一个
let str = ref('这是第一个数据');
watch(str, (newVal, oldVal) => {
    console.log(newVal, oldVal);
})

// (2)同时监听多个(用得不多)-------------------------
let str2 = ref('这是第二个数据');
watch([str, num], (newVal, oldVal) => {
    console.log(newVal, oldVal);
})

// (3)初始化监听-------------------------------------
let str3 = ref('这是第三个数据');
watch(num, (newVal, oldVal) => {
    console.log(newVal, oldVal);
}, {
    immediate: true
})

// (4)监听对象--------------------------------------
watch(obj, (newVal) => {
    console.log(newVal);
}, {
    immediate: true
})

// (5)监听具体的某一个key值,并且深度监听-----------
let obj = reactive({
    a: 1,
    b: 2,
    m: {
        c: 3
    }
})
const btn = () => {
    obj.a = 'xxx';
}
watch(() => obj.a, (newVal, oldVal) => {
    console.log(newVal, oldVal);
}, {
    immediate: true,
    deep: true
})

// (6)立即执行监听函数------------------------------
let str4 = ref('这是第四个数据');
watchEffect(() => {
    console.log(str4.value);
})

// (7)监听路由--------------------------------------
let router = userRouter();
watch(() => router.currentRoute.value, (newVal) => {
    console.log(newVal);
}, {
    immediate: true
})

生命周期钩子



你可能感兴趣的:(vue.js,前端,javascript)