Vue 3 在組件使用Vuex, vue-router參數

這兩天大概看了一下Vue 3的改版,於是就裝來玩看看,只要用vue cli 4就可以輕鬆將vue + vuex + vue-router 一併升級到支援現在的vue 3。

先全域安裝vue

npm install -g @vue/cli @vue/cli-service-global

開新的專案,建議先手選安裝vuex + Router

vue create hello-world

目前開的專案還會是舊的vue 2,要用下面指令即可升級到3,裡面程式碼他也會自動改寫

vue add vue-next

然後以前常在組件裡面用到router和vuex的變數,就用看看在Vue 3怎麼使用,如下

./views/About.vue

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <input v-model="capacity" />
    <p>
      Total:{{ capacity }}
    </p>
    <button @click="increaseTotal()">Increase Total</button>
    <p>{{ store.state.msg }}</p>
    <p>{{ route.params.id }}</p>
  </div>
</template>

<script>
import { ref } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";

export default {
  name: 'About',
  setup() {
    // data
    const total = ref(3);
    const store = useStore();
    const route = useRoute();
    function increaseTotal() { 
      total.value++;
      store.commit('setMsg', 'cooool');
    }
    return { total, increaseTotal, store, route }
  }
}
</script>

./store/index.js

import Vuex from 'vuex'

export default Vuex.createStore({
  state: {
    msg: "good",
  },
  mutations: {
    setMsg(state, value) {
      state.msg = value;
    }
  },
  actions: {
  },
  modules: {
  }
});

./router/index.js

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

const routes = [
{
  path: '/',
  name: 'Home',
  component: Home
},
{
  path: '/about/:id',
  name: 'About',
  // route level code-splitting
  // this generates a separate chunk (about.[hash].js) for this route
  // which is lazy-loaded when the route is visited.
  component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]

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

export default router

Leave a Reply

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *