Vue六(插件|Vuex的使用|购物车垮组件通信|Vue-route|路由跳转 携带数据 嵌套 守卫)

一、插件

插件的本质就是增强Vue 插件都是创建一个文件Plugins中写入index
本质:包含install方法的一个对象 install的第一个参数是Vuev第二个以后的参数是插件使用者传递的数据

import Vue from 'vue'

export default {
    // 1. vue 实例放一个变量
    install(minVue) {
            console.log(minVue)            // 防止冲突加上$
            Vue.prototype.$name='like'    // 类似于python 在类上放一个属性 所有对象都能取到

        // 2. 使用插件 加入混入
        Vue.mixin({
            data() {
                return {
                    name:'彭于晏',
                    age:20,
                };
            },
        });

        // 3.定义自定义指令
        Vue.directive('fbind',{
            bind(element,binding){
                element.value = binding.value;
            },
            inserted(element,binding){
                element.focus();
            },
            update(element,binding){
                element.value = binding.value;
            }
        });
    }}

在这里插入图片描述

二、Vuex

1)Vuex概念

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

Vuex执行流程图
在这里插入图片描述

2)搭建Vuex环境

import Vue from 'vue'		//引入Vue核心库
import Vuex from 'vuex'		//引入Vuex
Vue.use(Vuex)				//应用Vuex插件

const actions = {}			//准备actions对象——响应组件中用户的动作
const mutations = {}		//准备mutations对象——修改state中的数据
const state = {}			//准备state对象——保存具体的数据

export default new Vuex.Store({		//创建并暴露store
	actions,
	mutations,
	state
})

main.js中创建vm时传入store配置项

import store from './store'

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

3)Vuex简单使用

示例:修改state中数据年龄

store.index.js

import Vue from 'vue'
import Vuex from 'vuex'   // 安装过直接导入

Vue.use(Vuex)     // 使用Vuex插件

export default new Vuex.Store({
  state: {
    age:18,
  },
  mutations: {
    ADD(state,num,){
      console.log('###', num)
      state.age+=num }
  },
  actions: {
    add(context,num){
      console.log('---', context,num)       // 第一个参数传入context 内部有commit和dispatch
      context.commit('ADD',num)              // 调用commit会触发mutations中函数执行
    }                               // 封装性很强 这里可以做出判断 是否有权限改值 如果有权限就通过
  },
})

App.vue

<template>
  <div id="app">
    <h1>App Vuex</h1>
    <br>
    <h1>Vuex中state中的Age:-------{{ $store.state.age }}</h1>
    <button @click="clickSubmit">点我Vuex中的age+1</button>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {}
  },
  created() {
    console.log(this.$store)    // 所有Vuex操作都经过$store
  },
  methods: {
    clickSubmit() {
      this.$store.state.age++                       // 可以直接修改 但是不建议
      this.$store.dispatch("add",1)   // 按照流程 触发Vuex中的actions得函数执行 使用dispatch
    }
  }
}
</script>

在这里插入图片描述

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中定义变量(不建议)

4)购物车跨组件通信案例

Components/shoppingcar.vue-Goods.vue

	shoppingcar.vue
	
		<template>
		  <div>
		    <h1>购物车中商品数量为:{{$store.state.shoppingNum}}</h1>
		  </div>
		</template>
		
		<script>
		export default {
		  name: "shoppingCar"
		}
		</script>
		
		<style scoped>
		
		</style>
	
	Goods.vue
	
		<template>
			<div>
			  <ul>
			    <li>篮球----> <button @click="addShopcar">点我加入购物车</button></li>
			    <li>足球----> <button @click="addShopcar">点我加入购物车</button></li>
			    <li>台球----> <button @click="addShopcar">点我加入购物车</button></li>
			    <li>飞球----> <button @click="addShopcar">点我加入购物车</button></li>
			  </ul>
			</div>
		</template>
		
		<script>
		export default {
		  name: "Goods",
		  methods:{
		    addShopcar(){
		      this.$store.dispatch('addShopcar')    // 不是上面的addShopcar
		    }
		  }
		}
		</script>

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'   // 安装过直接导入

Vue.use(Vuex)     // 使用Vuex插件

export default new Vuex.Store({
    state: {
        shoppingNum: 0,
    },
    actions: {
        addShopcar(context) {
            context.commit('addShopcar')        // 调用mutations中函数执行 与mutations中名称一样不妨碍
        },
    },
    mutations: {
        addShopcar(state) {                 // 拿到数据值 += 1
            state.shoppingNum += 1
        },
    },
})

App.vue

<template>
  <div id="app">
    <h1>App Vuex</h1>
    <h1>购物车跨组件通信案例</h1>
    <shoppingCar></shoppingCar>
    <hr>
    <Goods></Goods>
  </div>
</template>

<script>
import Goods from "@/components/Goods";			// 导入组件
import shoppingCar from "@/components/shoppingCar";

export default {
  name: 'App',
  data() {
    return {}
  },
  methods: {
  components:{shoppingCar, Goods},
}
</script>

在这里插入图片描述

三、Vue-router

1)简单使用

router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'    // 导入包
import Home from "@/views/Home";	// 导入视图
import Goods from "@/views/Goods";

Vue.use(VueRouter)    // 使用路由插件

const routes = [
    {
        path: '/Home',      // 地址
        name: 'home',       // 网址名称
        component: Home     // 视图
    },
    {							//  如果有多个视图则写多个对象
        path: '/goods',
        name: 'goods',
        component: Goods
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

export default router

App.vue

<template>
  <div id="app">
    <router-view>
						// 需要添加上 router-view 这个时候访问路由名称即可
    </router-view>
  </div>
</template>
<script>

export default {
  name: 'App',
  data() {
    return {}
  },
  created() {
    console.log(this)   // 只要使用了路由组件 this中就有了 route router
  },
</script>

在这里插入图片描述

2)登录接口模拟

Login组件

<template>
  <div>
    <h1>登录页面</h1>
    <p>用户名:<input type="text" v-model="username"></p>
    <p>密码:<input type="text" v-model="password"></p>
    <button @click="submitLogin">登录</button>
  </div>
</template>

<script>
export default {
  name: "Login",
  data(){
    return{
      username:'',
      password:'',
    }
  },
  methods:{
    submitLogin(){
      console.log(this.username, this.password)
    }
  }
}
</script>

router.index.js

import Vue from 'vue'
import VueRouter from 'vue-router'    // 导入包
import login from "@/views/Login";

Vue.use(VueRouter)    // 使用路由插件

const routes = [
    {
        path: '/Login',
        name: 'login',
        component: login
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

export default router

在这里插入图片描述

3)路由跳转

<a href='/login'>登录页面</a>	// 不建议使用
<router-link to='login'>登录页面</router-link>		
<button @click='toLogin'>点我登录</button>
<router-link :to='login'>登录页面</router-link>		// 注意冒号

methods:{
	toLogin(){
		this.$router.push('login')
	}
}

data(){
	return{
		path:'login',	// 拓展性强
	}
}

4)路由跳转携带数据

两种情况:
	1:请求地址中
		<router-link to="/login/?name=like&age=20">去登录</router-link>
		组件中接收:this.$route.query.2:地址中
		<router-link to="/login/like">去登录</router-link>
		组件中接收:this.$route.params.

5)路由嵌套

创建两个子路由

<template>
<div>
  <h1>商品详情</h1>
  <p>I Like Basketabll</p>
</div>
</template>

<script>
export default {
  name: "GoodDetail"
}
</script>

index.js

import Vue from 'vue'
import VueRouter from 'vue-router'    // 导入包
import Goods from "@/views/Goods";
import GoodDetail from "@/views/GoodDetail";
import GoodList from "@/views/GoodList";

Vue.use(VueRouter)    // 使用路由插件

const routes = [
    {
        path: '/Goods',
        name: 'goods',
        component: Goods,
        children: [
            {
                name:'detail',
                path:'detail',
                component:GoodDetail
            },
            {
                name:'list',
                path:'list',
                component:GoodList
            },
        ],
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

export default router

views/Goods.vue

<template>
  <div>
    <h1>商品主页</h1>
    <p>
      <router-link to="/goods/detail"><span>详情</span></router-link>
      |
      <router-link to="/goods/list"><span>列表</span></router-link>
    </p>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Goods"
}
</script>

在这里插入图片描述

6)路由守卫

编写一个子路由被嵌套 然后进行路由守卫 看当前用户是否登录(查看localStorage里面是否有username) 登录则可以查看

添加LocalStorage

<template>
  <div>
    <h1>首页</h1>
    <button @click="toGoods">点我登录到商品页面</button>
    <br>
    <button @click="toLogin">点我登录</button>
  </div>
</template>

<script>
export default {
  name: "Home",
  methods:{
    toGoods(){
      this.$router.push('goods')
    },
    toLogin(){
      localStorage.setItem('name', 'like')
    }
  }
}
</script>

路由守卫

import Vue from 'vue'
import VueRouter from 'vue-router'    // 导入包
import Home from "@/views/Home";
import Goods from "@/views/Goods";
import GoodDetail from "@/views/GoodDetail";
import GoodList from "@/views/GoodList";
import shoppingCar from "@/views/shoppingCar";

Vue.use(VueRouter)    // 使用路由插件

const routes = [
    {
        path: '/Home',      // 地址
        name: 'home',       // 网址名称
        component: Home,     // 视图
    },
    {
        path: '/Goods',
        name: 'goods',
        component: Goods,
        children: [
            {
                name:'detail',
                path:'detail',
                component:GoodDetail
            },
            {
                name:'list',
                path:'list',
                component:GoodList
            },
            {
                name:'shoppingcar',
                path:'shoppingcar',
                component:shoppingCar
            },
        ],
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {
    console.log('前置路由守卫', to, from)

    if (to.name == 'shoppingcar') {
        let name = localStorage.getItem('name')
        if (name) {
            next()
        } else {            			// 前置守卫就是进行权限控制
            alert('不好意思没有权限')
        }
    } else {
        next()
    }

})


router.afterEach((to,from)=>{
	console.log('后置路由守卫',to,from)     // 后置守卫就是修改页面 title
	document.title = to.name
})
export default router

在这里插入图片描述

技术小白记录学习过程,有错误或不解的地方请指出,如果这篇文章对你有所帮助请点点赞收藏+关注谢谢支持 !!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LoisMay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值