【Vue3.0】- 入坑 - 全家桶

  • 本文主要內(nèi)容
    • 基于 vue-cli 快速搭建 Vue 3.0 項目

快速搭建 Vue 3.0 項目

版本

"dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.0.0-0",
    "vue-router": "^4.0.0-0",
    "vuex": "^4.0.0-0"
  }

升級vue-cli

npm install -g @vue/cli
vue -V
 vue/cli@4.5.4

創(chuàng)建項目

vue create vue3-demo

配置項目

  • 進入命令行
    • 選擇Manually select features
    • 勾選Router、VuexCSS Pre-processorsLinter / Formatter

目錄結(jié)構(gòu)

./src
├── App.vue
├── assets
│   └── logo.png
├── components
│   └── HelloWorld.vue
├── main.js
├── router
│   └── index.js
├── store
│   └── index.js
└── views
    ├── About.vue
    └── Home.vue

開發(fā)流程

新建頁面

  • src/views下創(chuàng)建Hello.vue
<template>
  <div class="page">Hello</div>
</template>

<script>
export default {

}
</script>

<style lang="scss" scoped>
.page {
  color: red;
}
</style>

創(chuàng)建路由

  • /src/router/index.js中創(chuàng)建路由配置
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('../views/About.vue')
  },
  {
    path: '/hello',
    name: 'Hello',
    component: () => import('../views/Hello.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

vue-router有哪些改變

  • 創(chuàng)建方式
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})
  • 構(gòu)建選項base
    • 傳給createWebHistory()(和其他模式) 的第一個參數(shù)作為base。
const router = createRouter({
  history: createWebHistory('/'),
  ...
})
  • 捕獲所有路由 ( /* ) 時,現(xiàn)在必須使用帶有自定義正則表達式的參數(shù)進行定義:/:catchAll(.*)
// 當(dāng)路由為 /user/a/b 時,捕獲到的 params 為 {"a": "a", "catchAll": "/b"}。
const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/user/:a:catchAll(.*)', component: component },
  ],
})
  • 如果使用<transition>,則可能需要等待router準(zhǔn)備就緒才能掛載應(yīng)用程序
app.use(router)
// Note: on Server Side, you need to manually push the initial location
router.isReady().then(() => app.mount('#app'))
  • push或者resolve一個不存在的命名路由時,將會引發(fā)錯誤,而不是導(dǎo)航到根路由 "/" 并且不顯示任何內(nèi)容
    • 原來,瀏覽器控制臺只會提示如下警告,并且url會跳轉(zhuǎn)到根路由 / 下。
    • 現(xiàn)在則報錯
  • 沒有全局 $router$route
    • 原先,通過在Vue根實例的router配置傳入router實例,下面這些屬性成員會被注入到每個子組件。
    • 現(xiàn)在 沒有this,也就不存在在 this.$router | $route這樣的屬性
     import { useRoute, useRouter } from 'vue-router'
     setup() {
      const route = useRoute()
      const router = useRouter()
      ...
      // router -> this.$router
      // route > this.$route
      router.push('/foo')
      console.log(route) // 路由對象信息
    }
    

狀態(tài)和事件綁定

  • Vue 3.0中定義狀態(tài)的方法改為類似React Hooks的方法
<template>
  <div class="page">
    <div>Hello</div>
    <div>{{count}}</div>
    <button @click="add">ADD</button>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const add = () => {
      count.value++
    }
    return {
      count,
      add
    }
  }
}
</script>
  • Vue 3.0中初始化狀態(tài)通過setup方法
  • 定義狀態(tài)需要調(diào)用ref方法
  • setup方法里,返回更新狀態(tài)的add方法,不再需要定義在methods
    • 更新count值的時候不能直接使用count++,而應(yīng)使用count.value++

計算屬性和監(jiān)聽器

<template>
  <div class="page">
    <div>Hello</div>
    <div>{{count}}</div>
    <div>double: {{doubleCount}}</div>
    <button @click="add">ADD</button>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const doubleCount = computed(() => count.value * 2)
    const add = () => {
      count.value++
    }
    watch(() => count.value, val => {
      console.log(`count is ${val}`)
    })
    return {
      count,
      doubleCount,
      add
    }
  }
}
</script>
  • 計算屬性computed是一個方法
    • 需要包含一個回調(diào)函數(shù)
    • 當(dāng)我們訪問計算屬性返回結(jié)果時,會自動獲取回調(diào)函數(shù)的值
  • 監(jiān)聽器watch同樣是一個方法
    • 它包含 2 個參數(shù),2 個參數(shù)都是function
      • 第一個參數(shù)是監(jiān)聽的值, 返回count.value
      • 第一個參數(shù)為值發(fā)生變化時觸發(fā)的回調(diào)

獲取當(dāng)前路由

  • Vue 3.0中通過getCurrentInstance方法獲取當(dāng)前組件的實例
  • 通過ctx屬性獲得當(dāng)前上下文
    • ctx.$routerVue Router實例
    • 里面包含了currentRoute,可以獲取到當(dāng)前的路由信息
import { getCurrentInstance } from 'vue';
// 獲取當(dāng)前實例
const { ctx } = getCurrentInstance();
// 獲取當(dāng)前路由
console.log(ctx.$router.currentRoute.value);

頁面跳轉(zhuǎn)

  • Vue 3.0setup中沒有 this
  • react-router,提供了useRouteruseRoute,分別對應(yīng)之前的this.$routerthis.$route
import { useRouter } from 'vue-router';
export default {
  setup() {
    ...
    const router = useRouter();
    const backHome = () => {
      router.push('/')
    }
    ...
  }
}

Vuex 集成

定義 Vuex 狀態(tài)

  • 修改src/store/index.js
import { createStore } from 'vuex'

export default createStore({
  state: {
    name: 'haha'
  },
  mutations: {
    setHelloName(state, value) {
      state.name = value;
    }
  },
  actions: {
  },
  modules: {
  }
})

獲取 Vuex 狀態(tài)

import { getCurrentInstance } from 'vue';
// 獲取當(dāng)前實例
const { ctx } = getCurrentInstance();
// vuex state
const name = computed(() => ctx.$store.state.name);

更新 Vuex 狀態(tài)

export default {
  setup() {
    // 獲取當(dāng)前實例
    const { ctx } = getCurrentInstance();
    // vuex state
    const name = computed(() => ctx.$store.state.name);
    const update = () => {
      ctx.$store.commit('setHelloName', 'haha -- ' + ctx.count );
    }
    ...
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容