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
    }
}

你可能感兴趣的:(vue3,javascript,前端,vue.js)