Vue系列(一)3.0尝鲜

5,515 阅读2分钟

写在前面:

在Vue3.0正式版发布之前,相信很多小伙伴和我一样期待着,因为尤雨溪大佬用TypeScript重构了它了,这意味着继续使用3.0,逼格只增不减😄,我们可以在.vue文件中愉快的使用ts了。项目基于Vite+Vue3.0+TypeScript。

1.官网copy下来的安装命令

yarn create vite-app hello-vue3
 yarn add typescript -D
 npx tsc --init

这里是分步创建ts环境的,执行完这些,打开项目将js文件改为ts文件,src目录下新建一个shim.d.ts文件如下:

declare module "*.vue" {  
  import { Component } from "vue";  
  const component: Component;  
  export default component;
}

这一步的目的是为了让ts环境下vue组件能够被正常解析,搭建完成的项目目录如下:

img
img

2.启动项目

 yarn dev

启动完成之后打开浏览器打开http://localhost:3000/就能看到你的3.0项目页面了,心急的小伙伴肯定要问了,怎么加路由,这里加的是Vue-Router 4.0测试版哦

3.添加路由

 yarn add vue-router@4.0

src目录下新建router目录,router目录下新建index.ts

import { createRouter, createWebHashHistory } from 'vue-router'
import HelloWorld from './../components/HelloWorld.vue'
const router = createRouter({  
  history: createWebHashHistory(),  
  routes: [
   {    
     path: '/',    
     component: HelloWorld  
   }
  ]
})
export default router

下面为Vue-Router3.x的使用方式:

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

Vue.use(VueRouter);

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

const router = new VueRouter({
  routes
});

export default router;

对比一下就会发现,4.x是直接调用createRouter方法,3.x则是new一个router对象,4.x更符合语义化,更贴合我们日常开发。细心的同学就会发现,4.x的路由模式是需要引入方法创建的,hash就是createWebHashHistory,history就是createWebHistory。

路由也引入了,那怎么能少了比格最高的Vuex呢...

4.添加状态管理

 yarn add vuex@4.0

在src目录下新建store文件夹,store下面新建index.ts文件,使用方法如下:

import { createStore } from 'vuex'
const store = createStore({  
  getters: {},  
  state: {    hello:'我是vuex'  },  
  actions: {},  
  mutations: {}
})
export default store

我们可以看到写法上和vue3.x没什么区别,和router一样都是引入createStore方法创建store对象,然后main.ts里面引用一下就好。

import { createApp } from 'vue'
import Router from './router/index'
import Store from './store/index'
import App from './App.vue'
import Vant from 'vant'
import 'vant/lib/index.css';
import './index.css'
const app = createApp(App)
app.use(Router)
app.use(Store)
app.use(Vant)
app.mount('#app')

为了让页面看上去更美观,引入了Vant3.x,以上为main.ts完整代码。页面使用状态示例:

const store = useStore();
const state = computed(() => store.state.hello);
const changeHello = () => store.commit("changeHello", "我是xx");
const asyncChange = () => store.dispatch("asyncChange", "我是xx");

5.简单使用Vant3.x搭建了一个移动端模板页面

img
img

6.结语

  • 目前Vue3.0还不适合快速应用于开发中,它需要一定时间的沉淀和学习,这样才能成为我们的开发利器;
  • 源代码地址奉上:github.com/YYDBBA/vue3…,喜欢的给个star哦~

本文使用 mdnice 排版