[day24][前端][實作] 用webpack自架Vue3環境(下)-Vue3(composition)



前情題要

在前兩篇中,已經能夠使用Vue3的幾乎所有功能了,這邊要開始實際運用啦!

在Vue3中重大的革新就是使用了"composition"去管理狀態,所以這邊就要試作hello composition的小功能拉!composition個人目前也還正在學習,真的還是不太懂。有興趣的可以看看這個網站重新認識 Vue.js | Kuro Hsu,有介紹Vue3的部分功能

首先建立資料夾"composition"然後建立一個"addNumber.js"的檔案

src\client\composition\addNumber.js

import { computed, ref, reactive } from 'vue';
export function addNumber(){
  const count = ref(0)
  const state = reactive({
    message: 'Vue3'
  })
  const doubleCount = computed(() => count.value * 2)
  const increment = e => {
    console.log(e)
    count.value += 10
    state.message = 'Vue3. GoGoGo!'
  }
  return {
    count,
    state,
    doubleCount,
    increment
  }
}

接著建立在"views"建立一個"addNumber.vue"

src\client\views\addNumber.vue

<template>
  <div class="container">
    hello {{state.message}}
    <div>count: {{count}}</div>
    <div>doubleCount: {{doubleCount}}</div>
    <button @click="increment" class="button">increment</button>
  </div>
</template>

<script>
import { addNumber } from '../composition/addNumber'
export default {
  setup () {  
    const { count, state, doubleCount, increment } = addNumber();
    return {
      count,
      state,
      doubleCount,
      increment
    }
  }
}
</script>

然後設定router增加這一頁

src\client\router\index.js

import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import home from '../views/home.vue'
import addNumber from '../views/addNumber.vue'
const routes = [
  {
    path: '/',
    name: 'home',
    component: home,
  },
  {
    path: '/addNumber',
    name: 'addNumber',
    component: addNumber,
  },

]
const router = createRouter({
  history: createWebHistory(),
  // history: createWebHashHistory(),
  routes
})
export default router;

接著在"app.vue"加上router連結

app.vue

<template>
  <div class="container">
    hello {{state.message}}
    <router-view
      class="main_container"
    />
    hello {{ vuexName }}
    <br>
    <router-link :to="{name: 'home'}">home</router-link>
    <br>
    <router-link :to="{name: 'addNumber'}">addNumber</router-link>
  </div>
</template>

這樣Vue3的"composition"最基礎用法就算是完成了!下一篇就是前端常用的css預處理器"scss"的用法拉!

githubday24

張貼留言

0 留言