一、Vuex的使用
Vuex基本使用
# 在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。# 使用步骤:1 在state中定义变量2 在组件中通过this.$store.dispatch('actions中定义的函数'),触发actions中得函数执行3 在actions中得函数中,调用 context.commit('mutations中定义的函数')4 在mutations中定义的函数实现真正的修改state中得数据5 页面中只要使用$store.state.变量,变量变化,页面就变化 实现了组件间通信6 注意:在组件中可以直接调用commit触发【mutations中定义的函数】在组件中可以直接修改state中定义变量
初始化数据、配置actions
、配置mutations
,操作文件store.js
//引入Vue核心库import Vue from 'vue'//引入Vueximport Vuex from 'vuex'//引用VuexVue.use(Vuex)const actions = {//响应组件中加的动作jia(context,value){// console.log('actions中的jia被调用了',miniStore,value)context.commit('JIA',value)},}const mutations = {//执行加JIA(state,value){// console.log('mutations中的JIA被调用了',state,value)state.sum += value}}//初始化数据const state = {sum:0}//创建并暴露storeexport default new Vuex.Store({actions,mutations,state,})
组件中读取vuex中的数据:$store.state.sum
组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)
或 $store.commit('mutations中的方法名',数据)
<template><div><hr>{{sum}}<button @click="handleClick">点我</button></div>
</template><script>export default {name: "App",data() {return {v:'xxx',sum:this.$store.state.sum};},methods:{handleClick(){// action中的方法名// this.$store.dispatch('jia',2)// console.log(this.$store.state.sum)//mutations中的方法名this.$store.commit('JIA',4)console.log(this.$store.state.sum)}}
};
</script>
Vuex执行流程图
二、Vue-route的使用
# 官方提供的用来实现SPA 的vue 插件:有了它以后,我们可以写很多页面组件,通过地址栏不同的路径显示不同的页面组件
# https://router.vuejs.org/zh/index.html
基本使用
# 使用步骤1 新建router/index.jsconst routes = [配置路由1,配置路由2]2 main.js中使用:之前已经写好了import router from './router'new Vue({...router,...}).$mount('#app')3 只需要写页面组件,配置路由即可4 在App.vue中加入<router-view></router-view>5 在浏览器访问const routes中配置的路径,就能看到对应的页面组件了
路由跳转
# 使用步骤:- 在html中使用<router-link :to="path">去登录</router-link>-在js中使用this.$router.push('goods')
路由跳转带参数
# 两种情况-带在请求地址中以 ?name=lqz&age=19-在地址中类似于django的分组 /goods/1/# 情况1:请求地址中-<router-link to="/login/?name=lqz&age=19">去登录</router-link>-组件中接受:this.$route.query.取# 情况2:地址中<router-link to="/login/lyf">去登录</router-link>-组件中接受:this.$route.params.取
路由嵌套
# 使用步骤:1 router/index.js 相应的路由中{path: '/goods',name: 'goods',component: Goods,children: [{path: 'list',component: GoodList},{path: 'detail',component: GoodDetail}]},2 必须要在Goods组件中,写<router-view></router-view>3 使用router-link标签跳转4 只会变更Goods下router-view包裹的位置
路由守卫
# 对路由进行权限控制# 前置路由守卫
router.beforeEach((to, from, next) => {console.log('前置路由守卫', to, from)if (to.name == 'shoppingcart') {let name = localStorage.getItem('name')if (name) {next()} else {alert('不好意思没有权限')}} else {next()}})
# 后置路由守卫
router.afterEach((to,from)=>{console.log('后置路由守卫',to,from)document.title = to.name
})