Vue基础第七篇

这篇具有很好参考价值的文章主要介绍了Vue基础第七篇。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、vuex的使用

1.概念

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

2.何时使用?

多个组件需要共享数据时

Vue基础第七篇

 3.搭建vuex环境

创建文件:src/store/index.js

   //引入Vue核心库
   import Vue from 'vue'
   //引入Vuex
   import Vuex from 'vuex'
   //应用Vuex插件
   Vue.use(Vuex)
   
   //准备actions对象——响应组件中用户的动作
   const actions = {}
   //准备mutations对象——修改state中的数据
   const mutations = {}
   //准备state对象——保存具体的数据
   const state = {}
   
   //创建并暴露store
   export default new Vuex.Store({
   	actions,
   	mutations,
   	state
   })

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

   ......
   //引入store
   import store from './store'
   ......
   
   //创建vm
   new Vue({
   	el:'#app',
   	render: h => h(App),
   	store
   })

4.基本使用

初始化数据、配置actions、配置mutations,操作文件store.js

   //引入Vue核心库
   import Vue from 'vue'
   //引入Vuex
   import Vuex from 'vuex'
   //引用Vuex
   Vue.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
   }
   
   //创建并暴露store
   export 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>


备注:若没有网络请求或其他业务逻辑,组件中也可以越过actions,即不写dispatch,直接编写commit

二、 Router使用

1 说明

  1. 官方提供的用来实现SPA 的vue 插件
  2. github: GitHub - vuejs/vue-router: 🚦 The official router for Vue 2
  3. 中文文档: http://router.vuejs.org/zh-cn/
  4. 下载: npm install vue-router --save
//引入VueRouter
   import VueRouter from 'vue-router'
   //引入Luyou 组件
   import About from '../components/About'
   import Home from '../components/Home'
   
   //创建router实例对象,去管理一组一组的路由规则
   const router = new VueRouter({
   	routes:[
   		{
   			path:'/about',
   			component:About
   		},
   		{
   			path:'/home',
   			component:Home
   		}
   	]
   })
   
   //暴露router
   export default router

2 相关API

VueRouter(): 用于创建路由器的构建函数

new VueRouter({
// 多个配置项
})

路由配置

routes: [
	{ // 一般路由
		path: '/about',
		component: About
	},
	{ // 自动跳转路由
		path: '/',
		redirect: '/about'
	}
]

注册路由

import router from './router'
new Vue({
	router
})

使用路由组件标签

<router-link>: 用来生成路由链接

<router-link to="/xxx">Go to XXX</router-link>

<router-view>: 用来显示当前路由组件界面

<router-view></router-view>

4 向路由组件传递数据

//1 路由配置
children: [
	{
	path: 'mdetail/:id',
	component: MessageDetail
	}
]
// 2 <router-link :to="'/home/message/mdetail/'+m.id">{{m.title}}</router-link>

// 3 this.$route.params.id

5 相关API

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

6 多级路由

  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>

7 命名路由(可以简化路由的跳转)

    {
      	path:'/demo',
      	component:Demo,
      	children:[
      		{
      			path:'test',
      			component:Test,
      			children:[
      				{
                name:'hello' //给路由命名
      					path:'welcome',
      					component:Hello,
      				}
      			]
      		}
      	]
      }
 <!--简化前,需要写完整的路径 -->
      <router-link to="/demo/test/welcome">跳转</router-link>
      
      <!--简化后,直接通过名字跳转 -->
      <router-link :to="{name:'hello'}">跳转</router-link>
      
      <!--简化写法配合传递参数 -->
      <router-link 
      	:to="{
      		name:'hello',
      		query:{
      		   id:666,
             title:'你好'
      		}
      	}"
      >跳转</router-link>

8. router-link的replace属性

作用:控制路由跳转时操作浏览器历史记录的模式
浏览器的历史记录有两种写入方式:分别为push和replace,push是追加历史记录,replace是替换当前记录。路由跳转时候默认为push
如何开启replace模式:News

9. 编程式路由导航

//$router的两个API
   this.$router.push({
   	name:'xiangqing',
   		params:{
   			id:xxx,
   			title:xxx
   		}
   })
   
   this.$router.replace({
   	name:'xiangqing',
   		params:{
   			id:xxx,
   			title:xxx
   		}
   })
   this.$router.forward() //前进
   this.$router.back() //后退
   this.$router.go() //可前进也可后退

10.路由守卫

  1. 作用:对路由进行权限控制
  2. 分类:全局守卫、独享守卫、组件内守卫

全局守卫

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
const router =  new VueRouter({
	routes:[
		{
			name:'guanyu',
			path:'/about',
			component:About,
			meta:{title:'关于'}
		},
		{
			name:'zhuye',
			path:'/home',
			component:Home,
			meta:{title:'主页'},
			children:[
				{
					name:'xinwen',
					path:'news',
					component:News,
					meta:{isAuth:true,title:'新闻'}
				},
				{
					name:'xiaoxi',
					path:'message',
					component:Message,
					meta:{isAuth:true,title:'消息'},
					children:[
						{
							name:'xiangqing',
							path:'detail',
							component:Detail,
							meta:{isAuth:true,title:'详情'},

							//props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。
							// props:{a:1,b:'hello'}

							//props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。
							// props:true

							//props的第三种写法,值为函数
							props($route){
								return {
									id:$route.query.id,
									title:$route.query.title,
									a:1,
									b:'hello'
								}
							}

						}
					]
				}
			]
		}
	]
})

//全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to,from,next)=>{
	console.log('前置路由守卫',to,from)
	if(to.meta.isAuth){ //判断是否需要鉴权
		if(localStorage.getItem('name')==='lqz'){
			next()
		}else{
			alert('名不对,无权限查看!')
		}
	}else{
		next()
	}
})

//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from)=>{
	console.log('后置路由守卫',to,from)
	document.title = to.meta.title || 'lqz系统'
})

export default router

独享守卫

// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import About from '../pages/About'
import Home from '../pages/Home'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建并暴露一个路由器
const router =  new VueRouter({
	routes:[
		{
			name:'guanyu',
			path:'/about',
			component:About,
			meta:{title:'关于'}
		},
		{
			name:'zhuye',
			path:'/home',
			component:Home,
			meta:{title:'主页'},
			children:[
				{
					name:'xinwen',
					path:'news',
					component:News,
					meta:{isAuth:true,title:'新闻'},
					beforeEnter: (to, from, next) => {
						console.log('独享路由守卫',to,from)
						if(to.meta.isAuth){ //判断是否需要鉴权
							if(localStorage.getItem('name')==='lqz'){
								next()
							}else{
								alert('名不对,无权限查看!')
							}
						}else{
							next()
						}
					}
				},
				{
					name:'xiaoxi',
					path:'message',
					component:Message,
					meta:{isAuth:true,title:'消息'},
					children:[
						{
							name:'xiangqing',
							path:'detail',
							component:Detail,
							meta:{isAuth:true,title:'详情'},

						}
					]
				}
			]
		}
	]
})


export default router

组件内守卫

  //进入守卫:通过路由规则,进入该组件时被调用
   beforeRouteEnter (to, from, next) {
   },
   //离开守卫:通过路由规则,离开该组件时被调用
   beforeRouteLeave (to, from, next) {
   }


	//通过路由规则,进入该组件时被调用
		beforeRouteEnter (to, from, next) {
			console.log('About--beforeRouteEnter',to,from)
			if(to.meta.isAuth){ //判断是否需要鉴权
				if(localStorage.getItem('school')==='atguigu'){
					next()
				}else{
					alert('学校名不对,无权限查看!')
				}
			}else{
				next()
			}
		},

		//通过路由规则,离开该组件时被调用
		beforeRouteLeave (to, from, next) {
			console.log('About--beforeRouteLeave',to,from)
			next()
		}

 路由器的两种工作模式

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

 localStorage和sessionStorage

<template>
  <div>
    <h1>操作localstorage,永久储存</h1>
    <button @click="addLocalstorage">增加</button>
    <button @click="getLocalstorage">查</button>
    <button @click="delLocalstorage">删除</button>
    <hr>
    <h1>操作sessiostorage,当前会话,关闭浏览器</h1>
    <button @click="addSessiostorage">增加</button>
    <button @click="getSessiostorage">查</button>
    <button @click="delSessiostorage">删除</button>
    <hr>
    <h1>操作cookie,有过期时间</h1>
    <button @click="addCookie">增加</button>
    <button @click="getCookie">查</button>
    <button @click="delCookie">删除</button>

  </div>
</template>

<script>
export default {
  name: "routerView",
  methods: {
    addLocalstorage() {
      var userinfo = {name: 'ch', age: 19}
      localStorage.setItem('userinfo', JSON.stringify(userinfo))
    },
    getLocalstorage() {
      var userinfo = localStorage.getItem('userinfo')
      console.log(JSON.parse(userinfo).name)
    },
    delLocalstorage() {
      localStorage.clear()
      localStorage.removeItem('userinfo')
    },
    addSessiostorage() {
      var userinfo = {name: '彭于晏', age: 19}
      sessionStorage.setItem('userinfo', JSON.stringify(userinfo))
    },
    getSessiostorage() {
      var userinfo = sessionStorage.getItem('userinfo')
      console.log(JSON.parse(userinfo).name)
    },
    delSessiostorage() {
      sessionStorage.clear()
      sessionStorage.removeItem('userinfo')
    },
    addCookie() {
      // 需要借助于第三方  vue-cookies
      // cnpm install -S vue-cookies
      this.$cookies.set('name', '刘亦菲', '300s')
    },
    getCookie() {
      console.log(this.$cookies.get('name'))
    },
    delCookie() {
      this.$cookies.remove('name')
    },
  }
}

</script>

<style scoped>

</style>

 main.js文章来源地址https://www.toymoban.com/news/detail-477982.html

//使用vue-cookies
import cookies from 'vue-cookies';

Vue.use(cookies)

到了这里,关于Vue基础第七篇的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 容器(第七篇)docker-consul

    consul服务器: 1. 建立 Consul 服务 mkdir /opt/consul cp consul_0.9.2_linux_amd64.zip /opt/consul cd /opt/consul unzip consul_0.9.2_linux_amd64.zip mv consul /usr/local/bin/ //设置代理,在后台启动 consul 服务端 consul agent -server -bootstrap -ui -data-dir=/var/lib/consul-data -bind=192.168.80.15 -client=0.0.0.0 -node=consul

    2024年02月08日
    浏览(49)
  • Qt文件系统源码分析—第七篇QFileSelector

    本文主要分析Windows平台,Mac、Linux暂不涉及 本文只分析到Win32 API/Windows Com组件/STL库函数层次,再下层代码不做探究 本文QT版本5.15.2 QTemporaryFile继承QFile QFile、QSaveFile继承QFileDevice QFileDevice继承QIODevice QIODevice、QFileSystemWatcher继承QObject QLockFile、QFileInfo、QDir、QFileSelector无任何继

    2024年02月07日
    浏览(29)
  • 第七篇——Apache Kafka的设计与实现

    作者:禅与计算机程序设计艺术 Apache Kafka是Apache软件基金会推出的一个开源分布式流处理平台,它最初由LinkedIn开发并于2011年9月正式发布,目前已成为 Apache 项目之一,是一个基于发布-订阅模式的分布式、高吞吐量、可容错、高可靠的消息系统,能够提供实时的消费和发送

    2024年02月08日
    浏览(26)
  • Vue系列第七篇:Element UI之el-main,el-table,el-dialog,el-pagination,el-breadcrumb等控件使用

    本篇实现主页面功能,包括主页面排版布局,学生管理模块实现,后台接口实现等功能。 目录 1.运行效果 1.1登录页面 1.2主页面  1.3学生管理 - 信息列表 1.4学生管理 - 信息管理  1.5学生管理 - 作业列表 1.6学生管理 - 作业管理 2.前端代码 2.1 代码结构  2.2 代码实现 3.后端代码

    2024年02月08日
    浏览(37)
  • 【HarmonyOS4.0】第七篇-ArkUI系统组件(二)

    鸿蒙开发系统组件详细剖析 进度条也是UI开发最常用的组件之一,ArkUI开发框架提供了两种类型的进度条: Progress 和 LoadingProgress ,前者可以精准指定进度,后者表示正在加载的状态,我们接下来对它们分别做下介绍。 5.1.Progress 5.1.1.Progress定义介绍 Progress 组件可以精确的设置

    2024年02月01日
    浏览(38)
  • 【FPGA入门】第七篇、FPGA实现VGA接口驱动

    目录 第一部分、实验结果  1、横的三色彩条效果 2、竖的三色彩条效果 第二部分、VGA驱动基本知识 1、VGA分辨率问题         2、VGA驱动波形 2.1、工业标准的时序波形图 2.2、比上面那张图更容易理解的图 2.3、每个区域对应的时间 2.4、不同分辨率的表格 3、VGA扫描范围问题

    2024年02月07日
    浏览(32)
  • Pyside6-第七篇-QLineEdit文本行编辑(内设案例)

    本篇Pyside6的第七篇,开启新功能了。单行文本编辑器。 源代码片段 ❝ 这里简单的告诉了你它可以怎么写。所以我们简单的试试。 ❞ 一个简单的单行文本示例

    2024年02月08日
    浏览(43)
  • C++类开发第七篇(详细说说多态和编译原理)

    多态性(polymorphism)提供接口与具体实现之间的另一层隔离,从而将”what”和”how”分离开来。多态性改善了代码的可读性和组织性,同时也使创建的程序具有可扩展性,项目不仅在最初创建时期可以扩展,而且当项目在需要有新的功能时也能扩展。 c++支持编译时多态(静态多

    2024年03月09日
    浏览(41)
  • [数据结构 -- 手撕排序算法第七篇] 递归实现归并排序

    目录 1、归并的思想 2、归并排序的思想 2.1 基本思想 2.2 图解分析 3、归并排序递归版本代码实现 3.1 代码解析 3.2 注意事项 3.2.1错误划分:[begin, mid-1],[mid, end] 3.2.2 正确划分:[begin, mid], [mid+1, end] 4、归并排序的测试 5、时间复杂度、空间复杂度分析 5.1 时间复杂度 5.2 空间复杂

    2024年02月16日
    浏览(35)
  • Shader学习第七篇:几种Unity的Shader的例子

    下面是几种Shader的例子,从简单到复杂,一步一步了解 Shader 的编写机制。 顶点/片元着色器 Vertex/Fragment Shader,下面我们介绍的示例就是这个。 表面着色器 Surface Shader ,而这个底层Unity也是转成了顶点/片元着色器 固定函数着色器 Fixed Function Shader (已弃用) 在一些低端设备使

    2024年02月09日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包