【vue讲解:ref、props、混入、插件、插槽使用、vuex、vue-router 、前端开源项目、localStorage,sessionStorage和cookie的使用】

0 ref

# 放在普通标签上
# 放在组件上


# 在vue项目中使用
	1 写在 组件上
    	<HelloWorld ref="my_hello_world"></HelloWorld>
    2 在父组件中使用:js
        handleClick() {
              console.log(this.$refs)
              this.$refs.my_hello_world.name  # 获取子组件中的name属性
              this.$refs.my_hello_world.showName()# 调用子组件中得方法
              this.name = this.$refs.my_hello_world.returnName()# 调用子组件中得方法取得返回值
            }

1 props

 # 1 使用方式一
props: ['msg'], #  基本用法,没有限制类型

#2  使用方式二 中级用法,有限制类型
props: {
     msg: {
       type: String, //类型
     }
   }, 
# 3 使用方式三:高级用法,有限制类型,限制是否必填,加默认值
  props: {
    msg: {
      type: String, //类型
      required: true, //必要性
      default: '老王' //默认值
    }
  }, 

2 混入

# 功能:可以把多个组件共用的配置提取成一个混入对象
	created,methods,data.....
    
    
# 举个栗子:记录用户查看每个页面所用时间(停留)
	全局每个页面都要写东西:
    	beforeCreate:启动一个定时器,每隔1s向后端发送一次请求
        destroyd:中销毁定时器
    

#如何使用?
	1 新建 mixin/index.js
    2 写代码:能写的配置项:
    	data,methods,watch....
    3 在组件中局部使用(如果有多个,在数组中继续追加即可)
    	import common from "@/common";
        export default {
          name: 'HomeView',
         	mixins: [common],
        }
    4 全局使用:main.js中
        # 使用全局混入
        import common from '@/common'
        Vue.mixin(common)
        # Vue.mixin(common1) // 使用多个混入
        
        
   5 以后再在组件中写 data,methods,新的不会影响,如果跟混入一样的会使用当前组件中得

3 插件

# 1 介绍
功能:用于增强Vue
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据

#2 咱们见过的第三方 vue的插件:
	vue-router
    vuex
    elementui
	

#3 补充:python 中和js中往类中放属性
class Person:
     pass
Person.name='lqz'
p=Person()
print(p.name)

# js中
new Vue()  # Vue类
Vue.prototype.$name='lqz' # 往类中加属性,跟python有些区别
# this.$router # this代指Vue实例
this.$name    # 从对象中取


# 4 自定义插件
	-1 plugins/index.js,写入代码
        export default {
            install(Vue) {
                console.log('######' + Vue)
                # 用插件干什么?
                # 1 设置全局变量--以后可以把axios做成全局,每个组件都直接使用this.$http
                Vue.prototype.$http = axios
                # 2 设置全局函数--->以后任意组件中  this.$add(2,3)
                Vue.prototype.$add = (a, b) => {
                    return a + b + 100
                }

                # 3 使用混入
                Vue.mixin({
                    data(){
                        return {
                            name:'lqz'
                        }
                    },
                    methods:{
                        showName(){
                            alert(this.name)
                        }
                    }
                })

               # 4 定义指令  v-for 内置指令,指令是可以自定义的   v-lqz
               # 5 定义全局组件---elementui做的--<el-button></el-button>
            }
        }
        
    -2 使用插件--main.js中
    	import plugin from '@/plugins'
		Vue.use(plugin)
        
        
        
# 5 看一下第三方插件的使用
	-vue-router:
    	-Vue.use(VueRouter)
        -以后在组件中this.$router 就拿到的是VueRouter 对象
        -以后在组件中 能拿到 this.$route  
        -全局组件:  <router-view/>
        
    -elementui:
    	-Vue.use(Elementui)
        -全局组件: <el-button></el-button>
		-全局变量:this.$message()

4 插槽使用

# 匿名插槽
-子组件中:
    <template>
      <div class="hello">
        <button @click="handleClick">组件--点我看控制台</button>
        <div>
           <slot></slot>
         </div>
    </template>
    
-父组件中:	
    <HelloWorld>
       <img src="../assets/img/1.png" alt="" width="200px" height="300px">
    </HelloWorld>
    # 或者写成
    <HelloWorld>
     <template>
       <img src="../assets/img/1.png" alt="" width="200px" height="300px">
     </template>
    </HelloWorld>

# 具名插槽
-子组件中:
    <template>
      <div class="hello">
        <button @click="handleClick">组件--点我看控制台</button>
        <div>
           <slot name='lqz'></slot>
         </div>
    </template>
    
-父组件中:	
    <HelloWorld>
       <img src="../assets/img/1.png" alt="" width="200px" height="300px" slot='lqz'>
    </HelloWorld>
    # 或者写成
    <HelloWorld>
     <template v-slot:lqz>
       <img src="../assets/img/1.png" alt="" width="200px" height="300px">
     </template>
    </HelloWorld>

4 vuex

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

# 组件间通信
	- 自定义属性
    - 自定义事件
    - ref属性:this.$refs.名字 拿到组件对象
    	父组件中:this.$refs.名字  拿到子组件对象
        子组件中:this.$parent     拿到父组件对象
    -vuex实现组件间通信---》不需要关注父子关系
    
# 使用: 创建项目已经安装了----》简单使用
	1 在store/index.js, 写代码---》详情见项目
       # 1 导入
        import Vue from 'vue'
        import Vuex from 'vuex'
        #  2 让vue使用插件
        Vue.use(Vuex)
        # 3 导出对象
        export default new Vuex.Store({
            state: {
                count: 0
            },
            getters: {},
            mutations: {},
            actions: {},
            modules: {}
        })
    
    2 在main.js中引入---》以后 任意组件中都会有 this.$store 
        import store from './store'
        new Vue({
            store,
            render: h => h(App)
        }).$mount('#app')
    3 在index.js 的state中定义变量--上面定义过了
         state: {
                count: 0
                },
        
    4 在任意组件中:取值,修改值--->任意组件都可以操作,操作的是同一个变量
    	js:this.$store.state.count
        html中:{{$store.state.count}}
	
            
            
            
# 麻烦使用  ---》官方推荐的
    #1 直接操作。不用了
    this.$store.state.count++
    # 2 通过actions
    this.$store.dispatch('addCountAction')
    # 3 通过mutations
    this.$store.commit('addCountMutations')

5 vue-router

#1 官方提供的用来实现SPA 的vue 插件
	页面跳转效果
    
#2 使用步骤:如果创建项目,没有安装vue-router,需要这么配置
	-1 cnpm install -S vue-router
    -2 新建router/index.js
    	import Vue from 'vue'
        import VueRouter from 'vue-router'
        import HomeView from '../views/HomeView.vue'
        Vue.use(VueRouter)
        const routes = [
            {
                path: '/',
                name: 'home',
                component: HomeView
            },
        ]
        const router = new VueRouter({
            mode: 'history',
            base: process.env.BASE_URL,
            routes
        })
        export default router
   -3 main.js中
	import router from './router'
    new Vue({
        router,
        render: h => h(App)
    }).$mount('#app')
   -4 以后再任意组件中,都有
	this.$router  # 路由对象,当时导出的
    this.$route   # 当前路由对象
   -5 在App.vue中
	  <div id="app">
        <router-view/>
      </div>
   -6 以后只要配置路由和页面组件的对应关系,在浏览器中访问地址即可



# 3 路由跳转
	-通过js跳转
    	 this.$router.push('/about')
    -通过组件跳转
        <router-link to="/about">
          任意标签
        </router-link>

# 4 路由跳转高级--传对象
	-通过js跳转时,传对象
    	# 1 使用方式1 
    	this.$router.push({
            name:'about'
        })
        # 2 使用方式2 
        this.$router.push({
            path:'/about'
        })
        # 3 使用方式三,带在地址栏中数据
        this.$router.push({
               name:'about',
               query:{name:'lqz',age:19}
            })
       # 4 取出地址栏中数据:
    		this.$route.query.名字
       # 5 使用方式四:在路径中解析出数据
    	-router/index.js中:
           {
            path: '/about/:id',
            name: 'about',
            component: AboutView
         }
         -组件中跳转
            this.$router.push({
               name:'about',
               params:{id:999}
            })
            this.$router.push('/about/666')
         -在另一个组件中取:
        	this.$route.params.名字
            
            
    -通过标签跳转传对象
    	<router-link :to="to_url"><button>标签跳转-传对象</button></router-link>
        # 变量定义
        to_url:{name:'about',query:{},params:{}}

5.1 路由嵌套–子路由

5.2 相关api

this.$router.push(path): 相当于点击路由链接(可以返回到当前路由界面)
this.$router.replace(path): 用新路由替换当前路由(不可以返回到当前路由界面)
this.$router.back(): 请求(返回)上一个记录路由
this.$router.go(-1): 请求(返回)上一个记录路由
this.$router.go(1): 请求下一个记录路由

5.3 路由守卫

作用:对路由进行权限控制

# 全局路由前置守卫
# 等后,才能跳转,是否有权限
# 全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
    console.log('前置路由守卫', to, from)
    if (to.name == 'home' || localStorage.getItem('name')) {
        next()
    } else {
        alert('您没有权限')
    }
})

5.4 路由两种工作模式

#  路由器的两种工作模式
    1 对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值。
    2 hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。
    
3 hash模式:
    地址中永远带着#号,不美观 。192.168.1.1#login    192.168.1.1#home  
    若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
    兼容性较好。
4 history模式:
    地址干净,美观 。   192.168.1.1/login    192.168.1.1/home  
    兼容性和hash模式相比略差。
    应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题

6 前端开源项目

# 1  后台管理
	-django-vue-admin:https://gitee.com/liqianglog/django-vue-admin/tree/main/web
    -https://gitee.com/yudaocode/yudao-ui-admin-vue2
# 2 移动端: vue 在uniapp上写
	-https://gitee.com/xany/yoshop2.0-uniapp  商城类
    -https://gitee.com/yudaocode/yudao-mall-uniapp

7 localStorage,sessionStorage和cookie的使用

# 浏览器可以存数据
	存在cookie中:过期时间,过期了,就清理掉了
    localStorage:永久有效,即便浏览器重启也有效,只能手动或代码删除
    sessionStorage:当次有效,关闭浏览器,就没了
    
    
    
# vue-cookies的使用
cnpm install vue-cookies -S
cookie.set('xx', 'yy', '7d')
console.log(cookie.get('xx'))
cookie.remove('xx')

# 具体使用
  methods: {
    saveLocalStorage() {
      // localStorage.setItem('name', 'xxx')
      // sessionStorage.setItem('name', '彭于')
      cookie.set('xx', 'yy', '7d')

    },
    getLocalStorage() {
      // console.log(localStorage.getItem('name'))
      // console.log(sessionStorage.getItem('name'))
      console.log(cookie.get('xx'))

    },
    deleteLocalStorage() {
      // localStorage.clear()
      // localStorage.removeItem('name')
      // sessionStorage.clear()
      // sessionStorage.removeItem('name')

      cookie.remove('xx')

    },
  }
  • 18
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

无敌开心

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

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

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

打赏作者

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

抵扣说明:

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

余额充值