vuex4和VueRouter4使用方法

描述:uex 4.0通过与3.x大致相同的API提供了Vue 3支持。唯一的重大变化插件的安装方式

vuex4

1.创建方式

import { createStore } from 'vuex'
export const store = createStore({
    state: {
        count:1
    },
    mutations: {
        add(state){
          state.count++ 
        },
        SET_COUNT(state, res) {
            state.count = res;
        }
    },
    actions:{
        setCount({commit}, res){
            commit('SET_COUNT', res)
        }
    }
})

2.注册

import { createApp } from 'vue'
import { store } from './store'
import App from './App.vue'
const app = createApp(App)
app.use(store)
app.mount('#app')

3.组件内使用方式

import { computed, watch } from 'vue';
import { useStore } from 'vuex';// 导入
export default{
    setup(){
        const store = useStore();
        const count = computed(() => store.state.count);
        // 如果方法定义在_mutations
        function add() {
            store.commit("add")
        }
        // 如果方法定义在_actions
        function setCount(){
            store.dispatch('setCount', 5);
        }
        // 监听
        watch(store.state.count, (newVal, oldVal) => {
        });
        return{
            count,
            add
        }
    }
}
vueRouter4

1.创建

import { createRouter, createWebHashHistory, createWebHistory } from "vue-router";
export default createRouter({
	// 模式has和history
	history: createWebHashHistory(),
  routes: [...],
});

2.注册

import { createApp } from "vue";
import router from "./router";
import App from './App.vue'
const app = createApp(App);
app.use(router);
app.mount("#app");

3.使用

import { useRoute, useRouter, onBeforeRouteLeave, onBeforeRouteUpdate,
onBeforeRouteEnter } from "vue-router";
export default{
 setup(){
     // 请注意,我们仍然可以访问$router和$route在模板中
    const router = useRouter();
    const route = useRoute();
    // 获取路由参数
    const routeQuery = route.query;
    jumped (path) {
        router.push({path: 'index', query: {})
    };
    return{
        jumped
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值