一、vuex的使用
1.概念
在Vue中實(shí)現(xiàn)集中式狀態(tài)(數(shù)據(jù))管理的一個(gè)Vue插件,對(duì)vue應(yīng)用中多個(gè)組件的共享狀態(tài)進(jìn)行集中式的管理(讀/寫),也是一種組件間通信的方式,且適用于任意組件間通信。
2.何時(shí)使用?
多個(gè)組件需要共享數(shù)據(jù)時(shí)
?3.搭建vuex環(huán)境
創(chuàng)建文件:src/store/index.js
//引入Vue核心庫(kù)
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//應(yīng)用Vuex插件
Vue.use(Vuex)
//準(zhǔn)備actions對(duì)象——響應(yīng)組件中用戶的動(dòng)作
const actions = {}
//準(zhǔn)備mutations對(duì)象——修改state中的數(shù)據(jù)
const mutations = {}
//準(zhǔn)備state對(duì)象——保存具體的數(shù)據(jù)
const state = {}
//創(chuàng)建并暴露store
export default new Vuex.Store({
actions,
mutations,
state
})
在main.js
中創(chuàng)建vm時(shí)傳入store
配置項(xiàng)
......
//引入store
import store from './store'
......
//創(chuàng)建vm
new Vue({
el:'#app',
render: h => h(App),
store
})
4.基本使用
初始化數(shù)據(jù)、配置actions
、配置mutations
,操作文件store.js
//引入Vue核心庫(kù)
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//引用Vuex
Vue.use(Vuex)
const actions = {
//響應(yīng)組件中加的動(dòng)作
jia(context,value){
// console.log('actions中的jia被調(diào)用了',miniStore,value)
context.commit('JIA',value)
},
}
const mutations = {
//執(zhí)行加
JIA(state,value){
// console.log('mutations中的JIA被調(diào)用了',state,value)
state.sum += value
}
}
//初始化數(shù)據(jù)
const state = {
sum:0
}
//創(chuàng)建并暴露store
export default new Vuex.Store({
actions,
mutations,
state,
})
組件中讀取vuex中的數(shù)據(jù):$store.state.sum
組件中修改vuex中的數(shù)據(jù):$store.dispatch('action中的方法名',數(shù)據(jù))
或?$store.commit('mutations中的方法名',數(shù)據(jù))
<template>
<div>
<hr>
{{sum}}
<button @click="handleClick">點(diǎn)我</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>
備注:若沒有網(wǎng)絡(luò)請(qǐng)求或其他業(yè)務(wù)邏輯,組件中也可以越過actions,即不寫dispatch
,直接編寫commit
二、?Router使用
1 說明
- 官方提供的用來實(shí)現(xiàn)SPA 的vue 插件
- github:?GitHub - vuejs/vue-router: ?? The official router for Vue 2
- 中文文檔:?http://router.vuejs.org/zh-cn/
- 下載:?
npm install vue-router --save
//引入VueRouter
import VueRouter from 'vue-router'
//引入Luyou 組件
import About from '../components/About'
import Home from '../components/Home'
//創(chuàng)建router實(shí)例對(duì)象,去管理一組一組的路由規(guī)則
const router = new VueRouter({
routes:[
{
path:'/about',
component:About
},
{
path:'/home',
component:Home
}
]
})
//暴露router
export default router
2 相關(guān)API
VueRouter(): 用于創(chuàng)建路由器的構(gòu)建函數(shù)
new VueRouter({
// 多個(gè)配置項(xiàng)
})
路由配置
routes: [
{ // 一般路由
path: '/about',
component: About
},
{ // 自動(dòng)跳轉(zhuǎn)路由
path: '/',
redirect: '/about'
}
]
注冊(cè)路由
import router from './router'
new Vue({
router
})
使用路由組件標(biāo)簽
<router-link>
: 用來生成路由鏈接
<router-link to="/xxx">Go to XXX</router-link>
<router-view>
: 用來顯示當(dāng)前路由組件界面
<router-view></router-view>
4 向路由組件傳遞數(shù)據(jù)
//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 相關(guān)API
this.$router.push(path): 相當(dāng)于點(diǎn)擊路由鏈接(可以返回到當(dāng)前路由界面)
this.$router.replace(path): 用新路由替換當(dāng)前路由(不可以返回到當(dāng)前路由界面)
this.$router.back(): 請(qǐng)求(返回)上一個(gè)記錄路由
this.$router.go(-1): 請(qǐng)求(返回)上一個(gè)記錄路由
this.$router.go(1): 請(qǐng)求下一個(gè)記錄路由
6 多級(jí)路由
routes:[
{
path:'/about',
component:About,
},
{
path:'/home',
component:Home,
children:[ //通過children配置子級(jí)路由
{
path:'news', //此處一定不要寫:/news
component:News
},
{
path:'message',//此處一定不要寫:/message
component:Message
}
]
}
]
// 跳轉(zhuǎn)
<router-link to="/home/news">News</router-link>
7 命名路由(可以簡(jiǎn)化路由的跳轉(zhuǎn))
{
path:'/demo',
component:Demo,
children:[
{
path:'test',
component:Test,
children:[
{
name:'hello' //給路由命名
path:'welcome',
component:Hello,
}
]
}
]
}
<!--簡(jiǎn)化前,需要寫完整的路徑 -->
<router-link to="/demo/test/welcome">跳轉(zhuǎn)</router-link>
<!--簡(jiǎn)化后,直接通過名字跳轉(zhuǎn) -->
<router-link :to="{name:'hello'}">跳轉(zhuǎn)</router-link>
<!--簡(jiǎn)化寫法配合傳遞參數(shù) -->
<router-link
:to="{
name:'hello',
query:{
id:666,
title:'你好'
}
}"
>跳轉(zhuǎn)</router-link>
8.?router-link的replace屬性
作用:控制路由跳轉(zhuǎn)時(shí)操作瀏覽器歷史記錄的模式
瀏覽器的歷史記錄有兩種寫入方式:分別為push和replace,push是追加歷史記錄,replace是替換當(dāng)前記錄。路由跳轉(zhuǎn)時(shí)候默認(rèn)為push
如何開啟replace模式:News
9. 編程式路由導(dǎo)航
//$router的兩個(gè)API
this.$router.push({
name:'xiangqing',
params:{
id:xxx,
title:xxx
}
})
this.$router.replace({
name:'xiangqing',
params:{
id:xxx,
title:xxx
}
})
this.$router.forward() //前進(jìn)
this.$router.back() //后退
this.$router.go() //可前進(jìn)也可后退
10.路由守衛(wèi)
- 作用:對(duì)路由進(jìn)行權(quán)限控制
- 分類:全局守衛(wèi)、獨(dú)享守衛(wèi)、組件內(nèi)守衛(wèi)
全局守衛(wèi)
// 該文件專門用于創(chuàng)建整個(gè)應(yīng)用的路由器
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'
//創(chuàng)建并暴露一個(gè)路由器
const router = new VueRouter({
routes:[
{
name:'guanyu',
path:'/about',
component:About,
meta:{title:'關(guān)于'}
},
{
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的第一種寫法,值為對(duì)象,該對(duì)象中的所有key-value都會(huì)以props的形式傳給Detail組件。
// props:{a:1,b:'hello'}
//props的第二種寫法,值為布爾值,若布爾值為真,就會(huì)把該路由組件收到的所有params參數(shù),以props的形式傳給Detail組件。
// props:true
//props的第三種寫法,值為函數(shù)
props($route){
return {
id:$route.query.id,
title:$route.query.title,
a:1,
b:'hello'
}
}
}
]
}
]
}
]
})
//全局前置路由守衛(wèi)————初始化的時(shí)候被調(diào)用、每次路由切換之前被調(diào)用
router.beforeEach((to,from,next)=>{
console.log('前置路由守衛(wèi)',to,from)
if(to.meta.isAuth){ //判斷是否需要鑒權(quán)
if(localStorage.getItem('name')==='lqz'){
next()
}else{
alert('名不對(duì),無權(quán)限查看!')
}
}else{
next()
}
})
//全局后置路由守衛(wèi)————初始化的時(shí)候被調(diào)用、每次路由切換之后被調(diào)用
router.afterEach((to,from)=>{
console.log('后置路由守衛(wèi)',to,from)
document.title = to.meta.title || 'lqz系統(tǒng)'
})
export default router
獨(dú)享守衛(wèi)
// 該文件專門用于創(chuàng)建整個(gè)應(yīng)用的路由器
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'
//創(chuàng)建并暴露一個(gè)路由器
const router = new VueRouter({
routes:[
{
name:'guanyu',
path:'/about',
component:About,
meta:{title:'關(guān)于'}
},
{
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('獨(dú)享路由守衛(wèi)',to,from)
if(to.meta.isAuth){ //判斷是否需要鑒權(quán)
if(localStorage.getItem('name')==='lqz'){
next()
}else{
alert('名不對(duì),無權(quán)限查看!')
}
}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
組件內(nèi)守衛(wèi)
//進(jìn)入守衛(wèi):通過路由規(guī)則,進(jìn)入該組件時(shí)被調(diào)用
beforeRouteEnter (to, from, next) {
},
//離開守衛(wèi):通過路由規(guī)則,離開該組件時(shí)被調(diào)用
beforeRouteLeave (to, from, next) {
}
//通過路由規(guī)則,進(jìn)入該組件時(shí)被調(diào)用
beforeRouteEnter (to, from, next) {
console.log('About--beforeRouteEnter',to,from)
if(to.meta.isAuth){ //判斷是否需要鑒權(quán)
if(localStorage.getItem('school')==='atguigu'){
next()
}else{
alert('學(xué)校名不對(duì),無權(quán)限查看!')
}
}else{
next()
}
},
//通過路由規(guī)則,離開該組件時(shí)被調(diào)用
beforeRouteLeave (to, from, next) {
console.log('About--beforeRouteLeave',to,from)
next()
}
?路由器的兩種工作模式
1 對(duì)于一個(gè)url來說,什么是hash值?—— #及其后面的內(nèi)容就是hash值。
2 hash值不會(huì)包含在 HTTP 請(qǐng)求中,即:hash值不會(huì)帶給服務(wù)器。
3 hash模式:
地址中永遠(yuǎn)帶著#號(hào),不美觀 。
若以后將地址通過第三方手機(jī)app分享,若app校驗(yàn)嚴(yán)格,則地址會(huì)被標(biāo)記為不合法。
兼容性較好。
4 history模式:
地址干凈,美觀 。
兼容性和hash模式相比略差。
應(yīng)用部署上線時(shí)需要后端人員支持,解決刷新頁面服務(wù)端404的問題文章來源:http://www.zghlxwxcb.cn/news/detail-477982.html
?localStorage和sessionStorage
<template>
<div>
<h1>操作localstorage,永久儲(chǔ)存</h1>
<button @click="addLocalstorage">增加</button>
<button @click="getLocalstorage">查</button>
<button @click="delLocalstorage">刪除</button>
<hr>
<h1>操作sessiostorage,當(dāng)前會(huì)話,關(guān)閉瀏覽器</h1>
<button @click="addSessiostorage">增加</button>
<button @click="getSessiostorage">查</button>
<button @click="delSessiostorage">刪除</button>
<hr>
<h1>操作cookie,有過期時(shí)間</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文章來源地址http://www.zghlxwxcb.cn/news/detail-477982.html
//使用vue-cookies
import cookies from 'vue-cookies';
Vue.use(cookies)
到了這里,關(guān)于Vue基礎(chǔ)第七篇的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!