77、elementui、使用vuex使用、Router使用、路由、localstorage、sessionstirage和cookie使用

183 阅读5分钟

elementui使用

文档:element.eleme.cn/#/zh-CN/com…

1.配置:
	1.下载:cnpm i element-ui -S
  2.在mian.js中引入
  	import ElementUI from 'element-ui';
		import 'element-ui/lib/theme-chalk/index.css';
		Vue.use(ElementUI);

vuex使用

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

2.vuex :状态管理器--->存数据(变量)的地方,所有组件都可以操作

vuex1.png

vuex2.png

vuex的简单使用

HomeView.vue

<template>
  <div class="home">
      <h1>1.vuex的使用-基本使用(操作state的数据)</h1>
      购物车商品的数量{{$store.state.num}}
      <br>
      <button @click = 'handleAdd'>点我购物车数量加{{count}}</button>
  </div>
</template>
<script>
export default {
  name: 'HomeView',
  data(){
      return{
          count:1
      }
  },
    methods:{
      handleAdd(){
          //1.直接操作
          this.$store.state.num +=this.count

          //2.1正统方式:通过dispatch触发actions
          this.$store.dispatch('add',this.count)  ////add 必须是action中得函数

          //3.直接操作mutations
          this.$store.commit('mAdd',this.count)

      }
    }
}
</script>

Store->index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {
    num:0
  },
  mutations: {
    //2.3修改state上的值
    mAdd(state,count){
      console.log(state)  //是一个对象
      console.log(count)
      state.num +=count
    }
  },
  actions: {
    add(context,count){
      //2.2使用commit,触发mutations中的函数
      console.log(context)  //一个对象,里面有commit、dispatch...
      console.log(count)
      context.commit('mAdd',count)  //// 会触发mutations中得mAdd的执行
    }
  },
})

组件间的通信

ShoppingCar.vue

<template>
<div>
    购物车商品:{{ $store.state.shopping_car }}
</div>
</template>

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

HomeView.vue

<template>
    <div class="home">
        <h1>组件间的通信</h1>
        <ul>
            <li>苹果
                <button @click="add('苹果')">+</button>
            </li>
        </ul>
        <ul>
            <li>橘子
                <button @click="add('橘子')">+</button>
            </li>
        </ul>
        <ul>
            <li>香蕉
                <button @click="add('香蕉')">+</button>
            </li>
        </ul>
        <hr>
        <h2>子组件</h2>
        <ShoppingCar></ShoppingCar>
    </div>
</template>

<script>

import ShoppingCar from "@/components/ShoppingCar.vue";
export default {
    name: 'HomeView',
    data() {
        return {
            count: 1,
        }
    },
    methods: {
        add(name){
            //1.直接操作
            // this.$store.state.shopping_car.push(name)

            //2.1 正统操作
            this.$store.dispatch('addcar',name)
        }

    },
    components:{
        ShoppingCar
    }

}
</script>

Store->index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    shopping_car:[]
  },

  mutations: {
    //2.3添加state上的值
    addcar(state,name){
      state.shopping_car.push(name)
    }

  },
  actions: {
    //2.2 通过commint 调mutations
    //一般子在这里发起ajax请求,检查库存够不够,如果不够,可以弹窗,return结束调,后面就不用走了
      addcar(context,name){
        context.commit('addcar',name)
      }
  },
})

Router使用

1.提倡单页面应用,需要做页面的跳转,就需要借助于Router实现页面组件的跳转
2.简单使用
		1.页面跳转
    2.写个页面组件
    3.在router--->index.js--->routes数组中加入一个路由即可
    
3.组件中实现页面跳转(两种方式)
		1.方式一:使用 router-link 标签,to 地址
         	<router-link to="/about"></router-link>
		2.方式二:js控制
        	this.$router.push('/about')
            
4.路由跳转时,可以使用对象
	1.通过对象跳转路由name形式: <router-link :to="{name:'about'}">
	2.通过对象跳转路由path形式: <router-link :to="{path:'/about'}">
	3.对象中可以有query属性,是个对象类型,会把里面的key-value拼到路径后面
	4.在另一个页面中取出地址栏中数据:console.log(this.$route.query)
	5.这种传递方式和 3 一样 <router-link to="/about?name=lqz&age=19">
	6.注意区分:
		this.$route:当前路由对象,当前路径,取传递数据。。。
		this.$router:整个路由对象,主要做跳转用
        
	7.路径中分割出参数
    	-配置:    
        	{
            path: '/detail/:pk',
            name: 'detail',
            component: DetailView
        	},
       -在路由中取:
        	this.$route.params.pk
            
8.路由跳转时,使用 7 的样子
    	-this.$router.push({name: 'detail', params: {pk: 999}})
        -<router-link :to="{name:'detail',params:{pk:88}}">
              
9.this.router 的一些方法
    this.$router.push(path): 相当于点击路由链接(可以返回到当前路由界面)
    this.$router.replace(path): 用新路由替换当前路由(不可以返回到当前路由界面)
    this.$router.back(): 请求(返回)上一个记录路由
    this.$router.go(-1): 请求(返回)上一个记录路由
    this.$router.go(1): 请求下一个记录路由

组件中实现页面跳转

HomeView.vue

<template>
    <div class="home">
        <h1>使用 router-link 标签跳转</h1>
        <h2>home页面qq</h2>
        <div>
            <router-link to="/about">
                <button>点我去about页面11</button>
            </router-link>
        </div>
        <hr>
        router-link标签中,:to带着一个对象:name/path/query
        <div>
            <router-link :to="{name:'about'}">
                <button>点我去about页面,name跳转</button>
            </router-link>
        </div>
        <div>
            <router-link :to="{path:'/about'}">
                <button>点我去about页面,path跳转</button>
            </router-link>
        </div>
        <div>
            <router-link :to="url_obj">
                <button>点我去about页面,带着query</button>
                <!--                http://localhost:8080/about?id=1&age=19-->
            </router-link>
        </div>
        <hr>
        <div>
            <router-link to="/about/?name=nana&&age=19">
                                <img src="https://img2.woyaogexing.com/2021/09/22/d9e5c102207f490b883e034db8657244!400x400.jpeg" alt=""
                     height="200px">
<!--                http://localhost:8080/about/?name=nana&age=19-->
            </router-link>

        </div>


        <hr>
        <h1>使用js跳转</h1>
        <button @click="GoAbout">js控制跳转到about</button>
        <hr>
        <button @click="GoGo">js控制跳转到about</button>
        <hr>



    </div>
</template>

<script>


export default {
    name: 'HomeView',
    methods: {
        GoAbout() {
            this.$router.push('/about')
            console.log(this.$router)
        },
        GoGo(){
            this.$router.push('/about/?name=nana&age=19')
        }
    },
    data() {
        return {
            url_obj: {
                name: 'about',
                query: {
                    id: 1,
                    age: 19
                }
            }
        }
    }


}
</script>

路径中分割出参数

LnView.vue

<template>
<div>
        <h1>ln页面</h1>
        <div>
        <router-link to="/books/1"><button>看pk为1的书</button></router-link>
        </div>
</div>
</template>

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

<style scoped>
</style>

DetailView.vue

<template>

  <div>
      <h1>某一本书的详情</h1>
  </div>

</template>

<script>
export default {
    name: "DetailView",
    created() {
        console.log(this.$route) //name: 'books', meta: {…}, path: '/books/1', hash: '', query: {…}, …}
        console.log(this.$route.params)  //{pk: '1'}
        console.log(this.$route.params.pk) //1
    }
}
</script>

<style scoped>

</style>

Router/index.js

    {
        path: '/books/:pk',
        name: 'books',
        component: DetailView
    },

多级路由

  routes:[
   	{
   		path:'/about',
   		component:About,
   	},
   	{
   		path:'/home',
   		component:Home,
   		children:[ //通过children配置子级路由
   			{
   				path:'news', //此处一定不要写:/news
   				component:News
   			},
   			{
   				path:'message',//此处一定不要写:/message
   				component:Message
   			}
   		]
   	}
   ]

// 跳转
<router-link to="/home/news">News</router-link>

使用步骤

1.新建一个页面组件(LqzView),配置路由
    	  {
            path: '/lqz',
            name: 'lqz',
            component: LqzView,
        },
2.在页面中,想再显示页面组件,实现点击切换的效果
    	   <h1>lqz页面</h1>
            <router-link to="lqz01">
              <button>lqz-01</button>
            </router-link>
            <router-link to="lqz02">
              <button>lqz-02</button>
            </router-link>

            <router-view>
            //以后这里变换页面组件,多级路由
            </router-view>
3.新建两个页面组件,Lqz01.vueLqz02.vue,配置路由children
        {
            path: '/lqz',
            name: 'lqz',
            component: LqzView,
            children: [ //通过children配置子级路由
                {
                    path: 'lqz01', //此处一定不要写:/news
                    component: Lqz01
                },
                {
                    path: 'lqz02',//此处一定不要写:/message
                    component: Lqz02
                }
            ]
        },

演示

ManyView.vue

<template>

  <div>
      <div>many页面</div>
      <router-link to="/many/nana-01">
          <button>去/many/nana-01页面</button>
      </router-link>
            <router-link to="/many/nana-02">
          <button>去/many/nana-02页面</button>
      </router-link>
      <hr>
      <router-view>

      </router-view>
  </div>
</template>

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

<style scoped>

</style>

Ln01.vue和Ln02.vue

<template>
  <div>
      <h1>nana-01页面</h1>
  </div>
</template>
<script>
export default {
    name: "Ln01"
}
</script>
<style scoped>
</style>
<template>
  <div>
      <h1>nana-02页面</h1>
  </div>
</template>
<script>
export default {
    name: "Ln02"
}
</script>
<style scoped>
</style>

Router/index.js

    {
        path: '/many',
        name: 'many',
        component: ManyView,
        children:[
            {
                path:'nana-01',
                component:Ln01
            },
            {
                path:'nana-02',
                component:Ln02
            },
        ]
    },

路由守卫

1.作用:对路由进行权限控制
2.分类:全局守卫、独享守卫、组件内守卫
		1.全局守卫:全局前置路由守卫、全局后置路由守卫
  		全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
			全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
    2.独享守卫
    3.组件内守卫
3.前置路由守卫,在进入路由之前做判断
4.写在router-index.js中,以后访问任意一个路由,都会执行这个代码
router.beforeEach((to, from, next) => {
    console.log('前置路由守卫', to, from)
    # 限制:要是访问lqz01,都不能跳转'
    # 可以进行登陆判断,如果没有登录,不能访问
    if (to.path == '/lqz/lqz01') {
        alert('你没有权限')
    } else {
        next() # 继续访问
    }

router-index.js

router.beforeEach((to,from,next)=>{
    console.log('前置路由守卫--to-->',to)  //前置路由守卫--to--> {name: 'home', meta: {…}, path: '/', hash: '', query: {…}, …}
    console.log('前置路由守卫--from-->',from)  //前置路由守卫--from--> {name: null, meta: {…}, path: '/', hash: '', query: {…}, …}
    if (to.path =='/many/nana-01'){
        alert('你没有权限')
    }else {
        next()
    }
})

路由的两种工作模式

1.对于一个url来说,什么是hash值?——>'#'及其后面的内容就是hash值。
2.hash值不会包含在 HTTP 请求中-->hash值不会带给服务器。
3 hash模式:
		"""
		const router = new VueRouter({
    mode: 'hash',
    base: process.env.BASE_URL,
    routes
})
		"""
    1.地址中永远带着#号,不美观 
    2.若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
    3.兼容性较好。
4.history模式:
		"""
		const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})
		"""
    1.地址干净,美观 
    2.兼容性和hash模式相比略差。
    3.应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题

localstorage、sessionstirage和cookie使用

1.前端存储数据
	1.登录成功,有token,存本地
  2.不登陆加购物车-->localstorage
    
2.前端可以存数据的位置:
	localstorage:永久存储,除非你删除,关闭浏览器,再打开还会在
  sessionstorage:只在当前会话生效,关闭浏览器,就没了
  cookie:有过期时间,到了过期时间,自动删除
    

localstorage

1.存:
    var obj = {"name":"xiaoming","age":"16"}
    localStorage.setItem("userInfo",JSON.stringify(obj));

2.取:
    var user = JSON.parse(localStorage.getItem("userInfo"))
3.删除:
    localStorage.remove("userInfo);
4.清空:
    localStorage.clear();
		localStorage.removeItem('userinfo')

HomeView.vue

<template>
    <div class="home">
        <h1>操作localstorage,永久存储</h1>
        <button @click="addLocalstorage">增加</button>
        <button @click="getLocalstorage">查</button>
        <button @click="deleteLocalstorage">删除</button>
    </div>
</template>
<script>
export default {
    name: 'HomeView',
    methods: {
        addLocalstorage(){
            alert(123)
            var userinfo = {name:'nana',age:19}
            localStorage.setItem('userinfo',JSON.stringify(userinfo))
        },
        getLocalstorage(){
            var userinfo = localStorage.getItem('userinfo')
            console.log(userinfo,typeof userinfo)  //{"name":"nana","age":19} string
            console.log(JSON.parse(userinfo).name) //nana
        },
        deleteLocalstorage(){
            localStorage.clear()
            localStorage.removeItem('userinfo')
        }
    },
    data() {
        return {

        }
    }
}
</script>

sessionstorage

1.存:
    var obj = {"name":"xiao","age":"16"}
    sessionStorage.setItem("userInfo",JSON.stringify(obj));

2.取:
    var user = JSON.parse(sessionStorage.getItem("userInfo"))
3.删除:
    sessionStorage.remove("userInfo);
4.清空:
    sessionStorage.clear();
		sessionStorage.removeItem('userinfo')

HomeView.vue

<template>
    <div class="home">
        <h1>操作sessiostorage,当前会话,关闭浏览器</h1>
        <button @click="addSessiostorage">增加</button>
        <button @click="getSessiostorage">查</button>
        <button @click="deleteSessiostorage">删除</button>
    </div>
</template>
<script>
export default {
    name: 'HomeView',
    methods: {
        addSessiostorage() {
            alert(123)
            var userinfo = {name: 'cx', age: 19}
            sessionStorage.setItem('userinfo', JSON.stringify(userinfo))
        },
        getSessiostorage() {
            var userinfo = sessionStorage.getItem('userinfo')
            console.log(userinfo, typeof userinfo)  //{"name":"nana","age":19} string
            console.log(JSON.parse(userinfo).name) //nana

        },
        deleteSessiostorage() {
            sessionStorage.clear()
            sessionStorage.removeItem('userinfo')
        },

    },
    data() {
        return {}
    }
}
</script>

cookie

<template>
    <div class="home">
        <h1>操作cookie,有过期时间</h1>
        <button @click="addCookie">增加</button>
        <button @click="getCookie">查</button>
        <button @click="deleteCookie">删除</button>
    </div>
</template>
<script>
export default {
    name: 'HomeView',
    methods: {
        addCookie() {
            // 需要借助与第三方 vue-cookies
            // 1.cnpm install -S
            //2.main.js引入
            this.$cookies.set('name','nana','300s')

        },
        getCookie() {
            console.log(this.$cookies.get('name'))

        },
        deleteCookie() {
            this.$cookies.remove('name')
        },

    },
    data() {
        return {}
    }
}
</script>

作业

把状态管理器的案例,换成两个组件中

ddGood.vue--组件

<template>
<div>
    <h1>AddGood组件</h1>
    <div>
        苹果<button @click="add('苹果')">+</button>
    </div>
        <div>
        橘子<button @click="add('橘子')">+</button>
    </div>
        <div>
        香蕉<button @click="add('香蕉')">+</button>
    </div>

</div>

</template>

<script>
export default {
    name: "AddGood",
    methods:{
        add(name){
            this.$store.dispatch('add',name)
        }
    }
}
</script>

<style scoped>

</style>

GoodList--组件

<template>
<div>
    添加的物品{{$store.state.goods_list}}
</div>
</template>

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

<style scoped>

</style>

HomeView.vue

<template>
    <div class="home">
    <AddGood></AddGood>
    <GoodList></GoodList>
    </div>
</template>

<script>
import AddGood from "@/components/AddGood.vue";
import GoodList from "@/components/GoodList.vue";

export default {
    name: 'HomeView',
    methods: {

    },
    data() {
        return {}
    },
    components:{
        AddGood,
        GoodList
    }
}
</script>

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goods_list:[]
  },
  mutations: {
  add(state,name){
    state.goods_list.push(name)
  }
  },
  actions: {
    add(context,name){
      context.commit('add',name)
    }
  },
})