Vue3.x接入Vuex,Vue-router

一、Vuex

用法近乎相同,{ mapState,mapMutations,mapActions,mapGetters }方法在option写法中用法依旧相同,在组合api中需要用 useStore 代替 $store,在Vue3中新增了{ provide,inject }方法,在多组件共用数据时提供了更方便的选择

1.安装

npm install vuex@next --save

2.编写store

/store/index.js

import { createStore } from "vuex";
export default createStore({
  state: {
    age: 18,
    name: "catii",
    sex: "boy",
  },
  mutations: {
    changeName(state, view) {
      state.name = view;
    },
  },
  actions: {
    changeNameAsync({ commit }, view) {
      setTimeout(() => {
        commit("changeName", view);
      }, 0);
    },
  },
  getters: {
    fullInfo(state) {
      return `${state.name} ${state.age} ${state.sex}`;
    },
  },
});

3.根组件挂载

/main.js

import store from "./store";
createApp(App).use(store).mount("#app");

4.组件引用

import { useStore } from "vuex";
import { defineComponent, toRefs } from "vue";

export default defineComponent({
  setup() {
    const store = useStore();
    // state
    const { age, sex, name } = toRefs(store.state);
    // mutations
    store.commit("changeName", "newName");
    // actions
    store.dispatch("changeNameAsync", "newName2");
    // getters
    const fullInfo = computed(() => store.getters.fullInfo);
    return {
      age,
      sex,
      name,
      fullInfo,
    };
  },
});

二、Vue-Router

用法与2.x版本几乎相同,使用{ useRouter, useRoute }分别代替option写法中的$router,$route

1.安装

``

2.创建router

/router/index.js

import { createRouter, createWebHashHistory } from "vue-router";
import PageA from "../components/page/PageB.vue";
import PageA from "../components/page/PageB.vue";
const routes = [
  {
    path: "/",
    redirect: "/PageA",
  },
  {
    path: "/PageA",
    component: PageA,
  },
  {
    path: "/PageB",
    component: PageB,
  },
];

export default createRouter({
  routes,
  history: createWebHashHistory(),
});

3. 挂载router

1.挂载router createApp(App).use(router).mount('#app')
2. 挂载

4. 组件中使用

import { defineComponent } from "vue";
import { useRouter, useRoute } from "vue-router";
export default defineComponent({
  setup() {
    const router = useRouter();
    const route = useRoute();

    router.push("/pageA");
  },
});

两个插件用法都没有太大变化,2.x,3.x写法都有兼容,接入友善。

你可能感兴趣的:(Vue3.x接入Vuex,Vue-router)