vue2路由与vuex

Vue2中的路由

cnpm install vue-router@3 --save
src–router–index.js

//引入Vue
import Vue from "vue";
//引入vue-router
import VueRouter from "vue-router";

// 使用VueRouter
Vue.use(VueRouter);

//配置路由
//1.准备组件(将页面引入进来)
import HomePage from "@/views/HomePage/HomePage.vue"
import FindPage from "@/views/FindPage/FindPage.vue"
import CategoryPage from "@/views/CategoryPage/CategoryPage.vue"
import CartPage from "@/views/CartPage/CartPage.vue"
import MinePage from "@/views/MinePage/MinePage.vue"

//2.定义路由(路由对应相应的页面)
//path:配置的路由接口  component:path对应的组件
let routes = [
    { path: "/home", component: HomePage },
    { path: "/find", component: FindPage },
    { path: "/category", component: CategoryPage },
    { path: "/cart", component: CartPage },
    { path: "/mine", component: MinePage }
]

//3.创建router实例,然后传routes配置
let router = new VueRouter({
    routes //缩写ES6:routes:routes
})

//4.暴露router对象
export default router

//在main.js中将router实例挂载到整个Vue实例对象上

main.js

import Vue from 'vue'
import App from './App.vue'
// 引入路由模块
import router from "@/router/index.js"

Vue.config.productionTip = false

new Vue({
    // 挂载router
    router,
    render: h => h(App),
}).$mount('#app')


// $mount("#app")同el:"#app"  都是挂载元素

//6.在App.vue中接收对应页面的路由(配置路由占位符)

App.vue

<template>
  <div id="app">
    <!-- router-view路由视图--接收对应页面的路由,必须配置,否则显示不出来 -->
    <!-- /home ==> HomePage -->
    <router-view></router-view>
    <TabBar></TabBar>
  </div>
</template>

vuex

cnpm install vuex@3 --save
src–store–index.js

// 引入vue和vuex
import Vue from "vue";
import Vuex from "vuex";
// 使用vuex
Vue.use(Vuex);

// 定义一个仓库来管理状态
let store = new Vuex.Store({
    // 定义状态数据的
    state: {
        num: 10
    },
    // 定义改变状态的唯一方法
    mutations: {
        // 改变state中的num
        changeNum(state) {
            state.num++;
        },
        // 接收参数改变state的num
        changeNum2(state, args) {
            state.num += args;
        }
    },
    // 执行异步操作
    actions: {
        // 和mutations相似,但是支持异步操作
        actChangeNum(context, data) {
            // 提交mutations中定义的方法,来改变state
            context.commit("changeNum2", data);
        }
    },
    // 派生出来的状态,相当于vuex的计算属性
    getters: {
        // getter相当于vuex的计算属性,必须加return
        getterNum(state) {
            return state.num * 10;
        }
    },
    // vuex的模块化处理
    modules: {

    }

});

// 暴露
export default store;

main.js挂载store

import store from "@/store/index.js"

Vue.config.productionTip = false

new Vue({
    router,
    store,
    render: h => h(App),
}).$mount('#app')

外部使用vuex

1.拿出store中的值
this.$store.state.num;
2.提交mutations
this.$store.commit("mutations中定义的方法","传递的数据");
3.派遣actions
this.$store.dispatch("actions中的方法","传递的参数");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值