Vue进阶用法3

Vue进阶用法3

Vuex 的使用

# vue的插件,增强了vue的功能,
在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信

# Vuex的使用流程
	-state:存数据的地址
    -actions:服务员,中转站
    -mutations:厨师,真正改state数据的地方
    
    -使用步骤:
    	1 在state中定义变量
        2 在组件中通过this.$store.dispatch('actions中定义的函数'),触发actions中得函数执行
        3 在actions中得函数中,调用 context.commit('mutations中定义的函数')
        4 在mutations中定义的函数实现真正的修改state中得数据
        5 页面中只要使用$store.state.变量,变量变化,页面就变化  实现了组件间通信
		6 注意:
        	-在组件中可以直接调用commit触发【mutations中定义的函数】
            -在组件中可以直接修改state中定义变量

Vue-router的使用

# 官方提供的用来实现SPA 的vue 插件:有了它以后,我们可以写很多页面组件,通过地址栏不同的路径显示不同的页面组件
# https://router.vuejs.org/zh/index.html

基本使用

# 使用步骤
	1 新建router/index.js
    	const 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
})
posted @ 2023-08-01 22:04  Joseph-bright  阅读(4)  评论(0编辑  收藏  举报