用法近乎相同,{ mapState,mapMutations,mapActions,mapGetters }
方法在option写法中用法依旧相同,在组合api中需要用 useStore 代替 $store,在Vue3中新增了{ provide,inject }
方法,在多组件共用数据时提供了更方便的选择
npm install vuex@next --save
/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}`;
},
},
});
/main.js
import store from "./store";
createApp(App).use(store).mount("#app");
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,
};
},
});
用法与2.x版本几乎相同,使用{ useRouter, useRoute }
分别代替option写法中的$router,$route
``
/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(),
});
1.挂载router createApp(App).use(router).mount('#app')
2. 挂载
import { defineComponent } from "vue";
import { useRouter, useRoute } from "vue-router";
export default defineComponent({
setup() {
const router = useRouter();
const route = useRoute();
router.push("/pageA");
},
});