目錄
1 vue的兩個(gè)特性
1.1 數(shù)據(jù)驅(qū)動視圖
1.2 雙向數(shù)據(jù)綁定?
2?MVVM工作原理
3?vue 的指令
3.1 內(nèi)容渲染指令
3.2?屬性綁定指令
3.3?事件綁定指令
3.4 事件修飾符?
3.5?按鈕修飾符
3.6?雙向數(shù)據(jù)綁定指令
3.7 條件渲染指令
3.8?列表渲染指令?
4?vue 的生命周期和生命周期函數(shù)?
4.1 生命周期&生命周期函數(shù)
4.2?組件生命周期函數(shù)的分類
4.3?生命周期函數(shù)特點(diǎn)
5 keep-alive
5.1 keep-alive的基本使用
5.2 keep-alive屬性
6?計(jì)算屬性和偵聽器
6.1 偵聽器
6.1.1 作用
6.1.2?偵聽器的格式
6.2?計(jì)算屬性
6.2.1 使用
6.2.2 注意
6.3?Computed 和 Watch 的區(qū)別
7?獲取組件/元素——refs
?7.1 ref的概念
?7.2?使用ref引用組件實(shí)例
8 綁定Class
8.1?對象語法:
8.1.1 傳給v-bind:class一個(gè)對象,以動態(tài)切換class
8.1.2? 在對象中傳入更多字段來動態(tài)切換多個(gè) class
8.1.3 綁定的數(shù)據(jù)對象不必內(nèi)聯(lián)定義在模板里
8.2 數(shù)組語法
8.2.1 把一個(gè)數(shù)組傳給?v-bind:class,以應(yīng)用一個(gè) class 列表
8.2.2 根據(jù)條件切換列表中的 class
8.3 用在組件上
8.4 總結(jié)
9?綁定內(nèi)聯(lián)樣式
9.1 對象語法
9.2?數(shù)組語法
10 組件通訊
10.1 父傳子用props
10.2?子傳父用$emit
10.3?兄弟組件之間的數(shù)據(jù)共享
11 插槽的使用
11.1?插槽基本用法
11.2? v-slot: 將內(nèi)容放在指定插槽
11.3?插槽后背(默認(rèn))內(nèi)容
11.4 具名插槽?
11.5 作用域插槽?
11.6?獨(dú)占默認(rèn)插槽的縮寫語法
11.7 動態(tài)插槽名
11.8?帶有 slot attribute 的具名插槽
12?路由的使用
12.1 前端路由的概念和原理
12.2 配置
12.3?把router對象掛載到main.js上
12.4 路由的基本使用
12.5??路由重定向
12.6?嵌套路由
12.7?動態(tài)路由匹配
12.8?捕獲所有路由或 404 Not found 路由
12.9?編程式導(dǎo)航跳轉(zhuǎn)
12.10?路由守衛(wèi)
12.10.1 全局前置守衛(wèi)
12.10.2 next 函數(shù)的 3 種調(diào)用方式
12.10.3?關(guān)于path和fullpath
12.11 路由傳參
12.11.1?query傳參
12.11.2 params傳參
12.11.3?路由props配置
13?狀態(tài)管理
13.1 狀態(tài)管理簡介
13.2 Vuex 的思想
13.3 核心狀態(tài)管理
13.4 在項(xiàng)目中使用
13.4.1 store一般有以下6個(gè)文件
13.4.2?vuex中 this.$store.dispatch() 與 this.$store.commit()方法的區(qū)別
13.4.3 實(shí)例1
13.4.4 實(shí)例2
(部分圖例引用黑馬教程及其他文章來源)
1 vue的兩個(gè)特性
1.1 數(shù)據(jù)驅(qū)動視圖
數(shù)據(jù)的變化會驅(qū)動視圖自動更新。
1.2 雙向數(shù)據(jù)綁定?
在網(wǎng)頁中,form負(fù)責(zé)采集數(shù)據(jù),Ajax負(fù)責(zé)提交數(shù)據(jù)。數(shù)據(jù)源的變化,會被自動渲染到頁面上;頁面上表單采集的數(shù)據(jù)發(fā)生變化的時(shí)候,會被 vue 自動獲取到,并更新到數(shù)據(jù)源中。
?
?
2?MVVM工作原理
?MVVM 是 vue 實(shí)現(xiàn)數(shù)據(jù)驅(qū)動視圖和雙向數(shù)據(jù)綁定的核心原理。MVVM 指的是 Model、View 和 ViewModel,它把每個(gè) HTML 頁面都拆分成了這三個(gè)部分,如圖所示:
?
注:
1、當(dāng)數(shù)據(jù)源發(fā)生變化時(shí),會被 ViewModel 監(jiān)聽到,VM會根據(jù)最新的數(shù)據(jù)源自動更新頁面的結(jié)構(gòu)。
2、當(dāng)表單元素的值發(fā)生變化時(shí),也會被VM監(jiān)聽到,VM會把變化過后最新的數(shù)據(jù)自動同步到Model數(shù)據(jù)源中。
3?vue 的指令
3.1 內(nèi)容渲染指令
內(nèi)容渲染指令用來輔助開發(fā)者渲染 DOM 元素的文本內(nèi)容。常用的內(nèi)容渲染指令有如下 3 個(gè):
- {{}}插值表達(dá)式:在實(shí)際開發(fā)中用的最多,只是內(nèi)容的占位符,不會覆蓋原有的內(nèi)容!
?(注意:插值表達(dá)式只能用在元素的內(nèi)容節(jié)點(diǎn)中,不能用在元素的屬性節(jié)點(diǎn)中?。?/p>
- v-text:會覆蓋元素內(nèi)部原有的內(nèi)容!
- v-html:不僅會覆蓋原來的內(nèi)容,而且可以把帶有標(biāo)簽的字符串,渲染成真正的HTML內(nèi)容!
3.2?屬性綁定指令
?v-bind:為元素的屬性動態(tài)綁定屬性值,則需要用到 v-bind 屬性綁定指令。
- 在 vue 中,可以使用v-bind:屬性為元素的屬性動態(tài)綁定值。
- 簡寫是英文的 "?: "。
- 在使用 v-bind 屬性綁定期間,如果綁定內(nèi)容需要進(jìn)行動態(tài)拼接,則字符串的外面應(yīng)該包裹單引號,例如:
<!--html-->
<a :href="'https://www.runoob.com/vue2/'+url">點(diǎn)擊跳轉(zhuǎn)vue菜鳥教程</a>
<!--script-->
const vm2=new Vue({
el:'#box2',
data:{
url:'vue-tutorial.html'
}
})
3.3?事件綁定指令
vue提供了v-on事件綁定指令,用于為DOM元素綁定事件監(jiān)聽。
- 注意:原生DOM對象有onclick、oninput、onkeyup等原生事件,替換為vue的事件綁定形式后,分別為v-on:click、v-on:input、v-on:keyup。
- 在v-on指令所綁定的事件處理函數(shù),可以接收事件參數(shù)對象event。
- $event是vue提供的特殊變量,用來表示原生的事件參數(shù)對象event。
<button @click="add">自增</botton>
<button @click="changeColor">變色</botton>
data(){
return{
count:'',
}
}
methods:{
add(){
this.count++;
},
changeColor(e){
e.target.style.backgroundColor='red';
}
}
3.4 事件修飾符?
3.5?按鈕修飾符
3.6?雙向數(shù)據(jù)綁定指令
3.7 條件渲染指令
- v-if、v-else、v-else-if條件性的渲染某元素,判定為true時(shí)渲染,否則不渲染
- 兩者區(qū)別:v-if條件不滿足不渲染,v-show條件不滿足令其display為none
<div v-if="score<60">不及格</div>
<div v-else-if="60<=score&&score<90">中等</div>
<div v-else="score>=90">優(yōu)秀</div>
<div v-show="true">display:block顯示</div>
<div v-show="false">display:none隱藏</div>
3.8?列表渲染指令?
?
?注意:不推薦在同一元素上使用 v-if 和 v-for?(詳情請查看官網(wǎng))
4?vue 的生命周期和生命周期函數(shù)?
4.1 生命周期&生命周期函數(shù)
生命周期概念:生命周期是指一個(gè)組件從創(chuàng)建 > 運(yùn)行 > 銷毀的整個(gè)過程,強(qiáng)調(diào)的是一個(gè)時(shí)間段。
生命周期函數(shù)概念:是由 vue 框架提供的內(nèi)置函數(shù),會伴隨著組件的生命周期,自動按次序執(zhí)行。
(注意:生命周期強(qiáng)調(diào)的是時(shí)間段,生命周期函數(shù)強(qiáng)調(diào)的是時(shí)間點(diǎn) 。)
4.2?組件生命周期函數(shù)的分類
4.3?生命周期函數(shù)特點(diǎn)
<template>
<div class="test-container">
<h3 id="myh3">Test.vue 組件 --- {{ books.length }} 本圖書</h3>
<p id="pppp">message 的值是:{{ message }}</p>
<button @click="message += '~'">修改 message 的值</button>
</div>
</template>
<script>
export default {
props: ['info'],
data() {
return {
message: 'hello vue.js',
books: []
}
},
watch: {
message(newVal) {
console.log('監(jiān)視到了 message 的變化:' + newVal)
}
},
methods: {
},
beforeCreate() {
// 創(chuàng)建階段的第1個(gè)生命周期函數(shù)。在這個(gè)函數(shù)無法訪問data、prors、methods
//很少有
},
created() {
// 組件只是在內(nèi)存中被創(chuàng)建好,但還未被渲染到頁面
// 經(jīng)常在它里面,調(diào)用 methods 中的方法,利用Ajax請求服務(wù)器的數(shù)據(jù)。并且,把請求到的數(shù)據(jù),轉(zhuǎn)存到 data 中,供 template 模板渲染的時(shí)候使用!
//可以訪問data、prors、methods
this.initBookList()
},
beforeMount() {
//只是在內(nèi)存上編譯好HTML
//將在渲染組件時(shí)執(zhí)行的操作
//很少用
},
mounted() {
//在此之前DOM還沒被渲染,但此時(shí)在mounted()時(shí)DOM已經(jīng)被渲染
// 如果要操作當(dāng)前組件的 DOM,最早只能在 mounted 階段執(zhí)行
//組件創(chuàng)建階段到此結(jié)束
},
beforeUpdate() {
//已經(jīng)根據(jù)拿到最新數(shù)據(jù),還沒完成組件DOM結(jié)構(gòu)的渲染
},
// 當(dāng)數(shù)據(jù)變化之后,為了能夠操作到最新的 DOM 結(jié)構(gòu),必須把代碼寫到 updated 生命周期函數(shù)中
updated() {
//已經(jīng)根據(jù)最新數(shù)據(jù),完成組件DOM結(jié)構(gòu)的渲染??梢员粓?zhí)行多次(因?yàn)閿?shù)據(jù)會變化多次)
//組件運(yùn)行階段到此結(jié)束
},
beforeDestroy() {
this.message = 'aaa'
},
destroyed() {
//組件銷毀階段到此結(jié)束
}
}
</script>
5 keep-alive
5.1 keep-alive的基本使用
?當(dāng)組件第一次被創(chuàng)建,會執(zhí)行created生命周期函數(shù),也會執(zhí)行activated生命周期函數(shù)。之后組件再被激活,只會觸發(fā)activated而不會觸發(fā)created。
使用:?
<keep-alive>
<組件名></組件名>
<keep-alive>
5.2 keep-alive屬性
- include包含的組件(可以為字符串,數(shù)組,以及正則表達(dá)式,只有名稱匹配的組件會被緩存)。
- exclude排除的組件(可以為字符串,數(shù)組,以及正則表達(dá)式,任何匹配的組件都不會被緩存)。
- max緩存組件的最大值(類型為字符或者數(shù)字,可以控制緩存組件的個(gè)數(shù))。
// 只緩存組件name為a和b的組件
<keep-alive include="a,b">
<component />
</keep-alive>
// 組件name為c的組件不緩存(可以保留它的狀態(tài)或避免重新渲染)
<keep-alive exclude="c">
<component />
</keep-alive>
// 如果同時(shí)使用include,exclude,那么exclude優(yōu)先于include, 下面的例子只緩存a組件
<keep-alive include="a,b" exclude="b">
<component />
</keep-alive>
// 如果緩存的組件超過了max設(shè)定的值5,那么將刪除第一個(gè)緩存的組件
<keep-alive exclude="c" max="5">
<component />
</keep-alive>
?注意:若組件沒有定義自己的name,則默認(rèn)以注冊組件時(shí)的名稱作為匹配條件。如果定義了name,會以name作為匹配條件。
6?計(jì)算屬性和偵聽器
6.1 偵聽器
6.1.1 作用
watch偵聽器允許開發(fā)者監(jiān)視數(shù)據(jù)的變化,從而針對數(shù)據(jù)的變化做特定的操作。
6.1.2?偵聽器的格式
1、方法格式的偵聽器(watch:{……}):
- 缺點(diǎn)1:無法在剛進(jìn)入頁面的時(shí)候自動觸發(fā)。
- 缺點(diǎn)2:如果偵聽的是一個(gè)對象,當(dāng)對象里的屬性值發(fā)生變化時(shí),不會觸發(fā)偵聽器。
2、對象格式的偵聽器 (watch(){……}):
- ?好處1:可以通過immediate選項(xiàng)讓偵聽器自動觸發(fā)。
?
- ?好處2:可以通過deep選項(xiàng),讓偵聽器深度監(jiān)聽對象中每個(gè)屬性的變化。
?
?
如果要偵聽對象里屬性的變化,可以如以下操作:
6.2?計(jì)算屬性
6.2.1 使用
1、定義計(jì)算屬性:
new Vue({
el:"#app",
data:{ ... },
methods:{ ... },
watch:{ ... },
computed:{
計(jì)算屬性名(){
計(jì)算過程
return 屬性值
}
}
})
2、在頁面上使用計(jì)算屬性:
<p>{{計(jì)算屬性名}}</p>
6.2.2 注意
1、computed 和 data同級,計(jì)算屬性寫在computed中;
2、寫起來像方法,用起來像屬性;
3、計(jì)算屬性雖然稱為屬性,但其本質(zhì)是一個(gè)函數(shù);
4、雖然計(jì)算屬性本質(zhì)是一個(gè)函數(shù),但是在頁面中使用計(jì)算屬性時(shí),不要加();
5、一定要有返回值;
6、可以使用data中的已知值;
7、只要跟計(jì)算屬性相關(guān)的數(shù)據(jù)發(fā)生了變化,計(jì)算屬性就會重新計(jì)算,不相關(guān)的屬性無論如何變化,都不會導(dǎo)致計(jì)算屬性變化;
8、計(jì)算屬性名不能和data中的數(shù)據(jù)重名(因?yàn)橐褂胐ata中的數(shù)據(jù))。
【頁面上使用】{{reversedMessage}}
【data中定義】msg:'New York'
【計(jì)算屬性】computed:{
reversedMsg (){
return this.msg.split('').reverse().join('')
}
}
6.3?Computed 和 Watch 的區(qū)別
1、computed計(jì)算屬性:
作用:
(1)解決模板中放入過多的邏輯會讓模板過重且難以維護(hù)的問題。例如兩個(gè)數(shù)據(jù)的拼接或字體顏色的判斷。
(2)它支持緩存,只有依賴的數(shù)據(jù)發(fā)生了變化,才會重新計(jì)算。例如模板中多次用到數(shù)據(jù)拼接可以用計(jì)算屬性,只執(zhí)行一次計(jì)算,除非數(shù)據(jù)發(fā)生變化。
(3)不支持異步,如果有異步操作,無法監(jiān)聽數(shù)據(jù)的變化。
(4)如果屬性值是函數(shù),默認(rèn)使用get方法,函數(shù)的返回值就是屬性的屬性值。還有一個(gè)set方法,當(dāng)數(shù)據(jù)變化時(shí)就會調(diào)用set方法。
(5)computed的值會默認(rèn)走緩存,計(jì)算屬性是基于它們的響應(yīng)式依賴進(jìn)行緩存的,也就是基于data聲明過,或者父組件傳遞過來的props中的數(shù)據(jù)進(jìn)行計(jì)算的。
2、watch偵聽器:
作用:
(1)它不支持緩存,數(shù)據(jù)變化時(shí),它就會觸發(fā)相應(yīng)的操作。
(2)支持異步監(jiān)聽。
(3)接受兩個(gè)參數(shù),第一個(gè)是最新的值,第二個(gè)是變化之前的值。
(4)監(jiān)聽data或者props傳來的數(shù)據(jù),發(fā)生變化時(shí)會觸發(fā)相應(yīng)操作。有兩個(gè)參數(shù):
? ? ? ? immediate:立即觸發(fā)回調(diào)函數(shù)。
? ? ? ? deep:深度監(jiān)聽,發(fā)現(xiàn)數(shù)據(jù)內(nèi)部的變化,在復(fù)雜數(shù)據(jù)類型中使用,例如數(shù)組中的對象發(fā)生變化。需要注意的是,deep無法監(jiān)聽到數(shù)組和對象內(nèi)部的變化。
3、總結(jié):
(1)computed 計(jì)算屬性 : 依賴其它屬性值,并且 computed 的值有緩存,只有它依賴的屬性值發(fā)生改變,下一次獲取 computed 的值時(shí)才會重新計(jì)算 computed 的值。
(2)watch 偵聽器 : 更多的是觀察的作用,無緩存性,類似于某些數(shù)據(jù)的監(jiān)聽回調(diào),每當(dāng)監(jiān)聽的數(shù)據(jù)變化時(shí)都會執(zhí)行回調(diào)進(jìn)行后續(xù)操作。
4、computed與watch的使用場景:
computed:是多對一,多個(gè)數(shù)據(jù)影響一個(gè)。當(dāng)需要進(jìn)行數(shù)值計(jì)算,并且依賴于其它數(shù)據(jù)時(shí),應(yīng)該使用 computed,因?yàn)榭梢岳?computed 的緩存特性,避免每次獲取值時(shí)都要重新計(jì)算。
watch:是一對多,一個(gè)數(shù)據(jù)發(fā)生變化,執(zhí)行相應(yīng)操作會影響多個(gè)數(shù)據(jù)。當(dāng)需要在數(shù)據(jù)變化時(shí)執(zhí)行異步或開銷較大的操作時(shí),應(yīng)該使用 watch,使用 watch 選項(xiàng)允許執(zhí)行異步操作 ( 訪問一個(gè) API ),限制執(zhí)行該操作的頻率,并在得到最終結(jié)果前,設(shè)置中間狀態(tài)。這些都是計(jì)算屬性無法做到的。
————————————————
版權(quán)聲明:本板塊為CSDN博主「前端路啊」的原創(chuàng)文章,原文鏈接:原文網(wǎng)址
7?獲取組件/元素——refs
?7.1 ref的概念
ref用來輔助開發(fā)者在不依賴于jQuery的情況下,獲取DOM元素或組件的引用。
<p ref="mytext">我會被refs獲取到</p>
<button @click="refTest">獲取mytext,改變其文本</button>
refTest(){
console.log(this.$refs.mytext);
this.$refs.mytext.innerHTML='我被獲取到啦'
},
?7.2?使用ref引用組件實(shí)例
【子組件 child.vue】
showTitle(){
alert('aaa');
}
【父組件 parent.vue】
<child ref="A">流程環(huán)節(jié)配置</child>
<button @click="B">點(diǎn)我彈出</button>
B(){
this.$refs.A.showTitle();
},
8 綁定Class
8.1?對象語法:
8.1.1 傳給v-bind:class一個(gè)對象,以動態(tài)切換class
<template>
<div>
<!-- class和style -->
<div v-bind:class="{ 'active': isActive, 'text-danger': hasError }">aa</div>
</div>
</template>
<script>
export default {
data() {
return {
isActive:true,
hasError:false
}
},
}
</script>
<style>
.active{
color:#e5c
}
.text-danger{
color: rgb(16, 212, 65);
}
</style>
上面的語法表示?active?這個(gè) class 存在與否將取決于數(shù)據(jù)isActive為true還是false。
8.1.2? 在對象中傳入更多字段來動態(tài)切換多個(gè) class
此外,v-bind:class?指令也可以與普通的 class attribute 共存。當(dāng)有如下模板:
<div
class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }"
></div>
data: {
isActive: true,
hasError: false
}
以上渲染的結(jié)果是:<div class="static active"></div>
當(dāng) isActive 或者 hasError 變化時(shí),class 列表將相應(yīng)地更新。例如,如果hasError=true,則渲染結(jié)果為:<div class="static active hasError"></div>
8.1.3 綁定的數(shù)據(jù)對象不必內(nèi)聯(lián)定義在模板里
<div v-bind:class="classObject"></div>
data: {
classObject: {
active: true,
'text-danger': false
}
}
8.2 數(shù)組語法
8.2.1 把一個(gè)數(shù)組傳給?v-bind:class,以應(yīng)用一個(gè) class 列表
<div v-bind:class="[class1,class2]"></div>
data: {
class1:'active',
class2:'box'
}
以上結(jié)果渲染為:<div class="active box"></div>
8.2.2 根據(jù)條件切換列表中的 class
在數(shù)組語法中也可以使用對象語法:
<div v-bind:class="[{ active: isActive }, errorClass]"></div>
這樣寫將始終添加 errorClass,但是只有在 isActive:true 時(shí)才添加 activeClass。
8.3 用在組件上
對于帶數(shù)據(jù)綁定 class的組件也同樣適用:
<my-component v-bind:class="{ active: isActive }"></my-component>
當(dāng)?isActive?為 true?時(shí),class="組件原來的樣式 active"
8.4 總結(jié)
方式一:v-bind:class="{ '類名1': data1, '類名2': data2,…… }"
data(){
return{
data1:false/true,
data2 : false/true
……
}
}
方式二:v-bind:class="對象名"
data(){
return{
對象名:{
"類名1":false/true,
"類名2":true/true,
……
}
}
}
方式三:v-bind:class="[class1,class2,class3,……]"
data(){
return{
class1:'類名1',
class2:'類名2',
……
}
}
9?綁定內(nèi)聯(lián)樣式
9.1 對象語法
v-bind:style?的對象語法十分直觀——看著非常像 CSS,但其實(shí)是一個(gè) JavaScript 對象。CSS property 名可以用駝峰式 (camelCase) 或短橫線分隔 (kebab-case,記得用引號括起來) 來命名:
<div v-bind:style="{color:textColor,fontSize:textSize+ 'px'}">aa</div>
data() {
return {
textColor:'#aa8',
textSize:30
}
},
?直接綁定到一個(gè)樣式對象通常更好,這會讓模板更清晰:
<div v-bind:style="styleObject"></div>
data: {
styleObject:{
color:'#fff',
fontSize:25+'px',
}
}
9.2?數(shù)組語法
v-bind:style?的數(shù)組語法可以將多個(gè)樣式對象應(yīng)用到同一個(gè)元素上:
<div v-bind:style="[styleObject1,styleObject2]"></div>
data: {
styleObject1: {
color: 'red',
fontSize:13+'px'
},
styleObject2: {
width: 100+'px',
height:130+'px'
}
}
10 組件通訊
10.1 父傳子用props
- 第一步:引入子組件。
- 第二步:在數(shù)據(jù)源中定義要傳入子組件的數(shù)據(jù)parentMsg。
- 第三步:在使用child組件時(shí)傳入parentMsg。<child :自定義屬性名="parentMsg"></child>。
- 第四步:在子組件中,要 props:['自定義屬性名']來接收傳過來的參數(shù)。
?【父組件】
<template>
<div>
<h2>parent</h2>
<!--3、傳入parentMsg-->
<child :visible="visible"></child>
</div>
</template>
<script>
//1、引入子組件
import child from './child.vue'
export default {
data() {
return {
//2、定義要傳入子組件的數(shù)據(jù)parentMsg
visible:'true'
}
},
components:{
child
}
}
</script>
【子組件】
<template>
<div>
{{visible}}
</div>
</template>
<script>
export default {
name:'child',
//使用prors對象可以設(shè)置配置項(xiàng),使用prors數(shù)組不可以。
// props:{
// parentMsg:{
// type:String,
// default:'i am child'
// }
// }
props:['visible']//接收
}
</script>
10.2?子傳父用$emit
emit使用方法:this.$emit(‘自定義事件名’,所需要傳的值)
- 第一步:首先在子組件中定義一個(gè)事件,并且使用emit發(fā)送給父組件,在示例中子組件使用的click事件觸發(fā)發(fā)送自定義事件(sendmsg)。
- 第二步:在父組件中需要定義方法(getmsg)接受自定義事件(sendmsg):
- 第三步:在使用子組件時(shí),<child @sendmsg="getmsg"></child>。
?【子組件】發(fā)送值
<template>
<div>
<button @click="childmsg">點(diǎn)我試試</button>
</div>
</template>
<script>
export default {
name:'child',
data() {
return {
msg:"This is the first word from child"
}
},
methods:{
//點(diǎn)擊按鈕則向父組件傳自定義事件sendmsg,childmsg
childmsg(){
this.$emit('sendmsg',this.msg)
}
}
}
</script>
【父組件】接收值
<template>
<div>
<child @sendmsg="getmsg"></child>
</div>
</template>
<script>
import child from './child.vue'
export default {
data() {
return {
}
},
components:{
child
},
methods:{
getmsg(val){
console.log(val)
}
}
}
</script>
總結(jié):
- 父傳子【父中定義要傳的值A(chǔ),通過:B="A"傳給子,子用props:["B"]接收,但props只讀,要C:this.B,在子組件中就可以對C進(jìn)行操作(可以理解為B只是C的初始值)】
- 子傳父【在子中的某個(gè)事件?this.$emit('傳給父組件的事件E',要傳的值G),父用@E="F"接收并使用,在F中可以如下定義:F(val){……},此處會把G作為實(shí)參傳給val】
10.3?兄弟組件之間的數(shù)據(jù)共享
- ?第一步:在兄弟組件同目錄下創(chuàng)建eventBus.js,然后創(chuàng)建vue實(shí)例:
import Vue from 'vue'
export default new Vue()
-
第二步:在【兄弟組件A】中,引入eventBus.js > 定義數(shù)據(jù)msg > 編寫方法用于發(fā)送msg:
import bus from './eventBus.js'
<button @click="sendMsg">
export default{
data(){
return{
msg:'hello'
}
},
methods:{
sendMsg(){
bus.$emit('share',this.msg);
}
}
}
- 第三步:在【兄弟組件B】中,引入eventBus.js>定義數(shù)據(jù)newMsg>編寫方法用于接收msg和賦值給newMsg:
import bus from './eventBus.js'
<button @click="sendMsg">
export default{
data(){
return{
newMsg:[]
}
},
created:{
bus.$on('share',val=>{
this.newMsg=val;
})
}
}
11 插槽的使用
總體思想:父組件指定內(nèi)容,子組件渲染內(nèi)容。
11.1?插槽基本用法
【父組件】
<Left>
<p>這是在 Left 組件聲明的p標(biāo)簽</p>
</Left>
【子組件】
<div class="left-box">
<span>Left 組件</span>
<!-- 在 Left 組件內(nèi)聲明一個(gè)插槽區(qū) -->
<slot></slot>
</div>
11.2? v-slot: 將內(nèi)容放在指定插槽
- vue 官方規(guī)定:每一個(gè) slot 插槽都要有一個(gè) name 名稱
- 如果省略了 slot 的name 則有一個(gè)默認(rèn)名稱 default
- 默認(rèn)情況下,使用組件時(shí)提供的內(nèi)容會被填充到 name 為 default 的插槽內(nèi)
【將內(nèi)容放在指定的插槽內(nèi)】:
- 使用 v-slot:xxx, 其中 xxx為插槽 name 值,只能放在 標(biāo)簽內(nèi)
- 使用 標(biāo)簽包裹
- 是一個(gè)虛擬標(biāo)簽,只起到包裹性質(zhì)的作用,不會被渲染為實(shí)質(zhì)性的 html 元素
- v-slot:xxx 可以簡寫為 #xxx
【父組件】
<Left>
<template v-slot:mySlot>
<p>這是在 Left 組件聲明的p標(biāo)簽</p>
</template>
</Left>
【子組件】
<div style="color:#33e;background:#ee2">
<slot name="mySlot"></slot>
</div>
11.3?插槽后背(默認(rèn))內(nèi)容
- 當(dāng)使用組件指定了插槽內(nèi)容時(shí),優(yōu)先顯示指定的內(nèi)容
- 當(dāng)沒有指定內(nèi)容時(shí),渲染 slot 標(biāo)簽內(nèi)的默認(rèn)內(nèi)容
11.4 具名插槽?
當(dāng)需要將內(nèi)容置入不同組件時(shí),要用帶有name屬性的插槽:
<HeaderVue #header>我是來自header的插槽</HeaderVue>
<Main>
<template v-slot:box1>我是來自child的插槽box1</template>
<template v-slot:box2>我是來自child的插槽box2</template>
</Main>
- 注意?v-slot?只能添加在<template>上
- v-slot 也有縮寫,即把參數(shù)之前的所有內(nèi)容 (v-slot:) 替換為字符 #。例如 v-slot:header 可以被重寫為 #header
11.5 作用域插槽?
條件:在封裝組件時(shí),為預(yù)留的 <slot> 提供屬性對應(yīng)的值
格式:
子組件:<slot v-bind:username='username' name='box1'></slot>
父組件:<template v-slot:box1='username_prors'>
在封裝組件時(shí),為預(yù)留的 <slot> 提供屬性對應(yīng)的值,叫做作用域插槽。這些屬性對應(yīng)的值可以在父組件中訪問到,默認(rèn)為空對象。
【子組件中】
<div>
<slot v-bind:user="user" name="box3"></slot>
<slot v-bind:msg="hello world" name="box4"></slot>
</div>
data(){
return:{
user:{
firstname:'lan',
lastname:'chun'
}
}
}
【父組件中】
<子組件名>
<template v-slot:box3="slotProps1">
{{slotProps1.user.firstname}}
{{slotProps1.user.lastname}}
</template>
<template v-slot:box4="slotProps2">
{{slotProps2.msg}}
</template>
</子組件名>
11.6?獨(dú)占默認(rèn)插槽的縮寫語法
條件:被提供的內(nèi)容只有默認(rèn)插槽時(shí)
格式:直接寫在組件里
當(dāng)被提供的內(nèi)容只有默認(rèn)插槽時(shí),組件的標(biāo)簽可以被當(dāng)作插槽的模板來使用,可以把?v-slot?直接用在組件上:
<子組件名 v-slot:default="slotProps">
{{ slotProps.user.firstName }}
</子組件名>
- 當(dāng)被提供的內(nèi)容只有默認(rèn)插槽時(shí),可以用 v-slot:default=" ",也可以直接用縮寫v-slot=" "。
- 默認(rèn)插槽的縮寫語法不能和具名插槽混用,因?yàn)樗鼤?dǎo)致作用域不明確。
- 只要出現(xiàn)多個(gè)插槽,請始終為所有的插槽使用完整的基于 的語法,如下:
<current-user>
<template v-slot:default="slotProps">
{{ slotProps.user.firstName }}
</template>
<template v-slot:other="otherSlotProps">
...
</template>
</current-user>
11.7 動態(tài)插槽名
動態(tài)指令參數(shù)也可以用在 v-slot 上,來定義動態(tài)的插槽名:
<base-layout>
<template v-slot:[dynamicSlotName]>
...
</template>
</base-layout>
11.8?帶有 slot attribute 的具名插槽
直接把 slot attribute 用在一個(gè)普通元素上:
<base-layout>
<h1 slot="header">Here might be a page title</h1>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<p slot="footer">Here's some contact info</p>
</base-layout>
12?路由的使用
url地址里,‘#’及以后的部分稱為哈希地址,可以在控制臺用location.hash打印哈希地址
12.1 前端路由的概念和原理
1)用戶點(diǎn)擊頁面上的路由鏈接
2)導(dǎo)致url地址的Hash值變化
3)前端路由監(jiān)聽到Hash地址的變化
4)前端路由把當(dāng)前Hash地址對應(yīng)的組件渲染到瀏覽器中
12.2 配置
- 第一步:安裝vue-router包npm install vue-router@3.5.2?-S
- 第二步:創(chuàng)建路由模塊。創(chuàng)建router文件夾,在文件夾下建立index.js
//1、導(dǎo)入Vue和VueRouter的包,定義 (路由) 組件
import Vue from 'vue'
import VueRouter from 'vue-router'
import Prize from '@/components/Prize.vue'
import Home from "@/components/Main.vue";
import parent from '@/components/parent'
//2、調(diào)用Vue.use()函數(shù),把VueRouter安裝為vue插件
Vue.use(VueRouter);
//3、創(chuàng)建路由的實(shí)例對象
const router =new VueRouter({
routes:[
{
path:'/home',
component:Home
},
{
path:'/prize',
component:Prize,
},
{
path:'/parent',
component:parent
}
]
})
//4、向外共享路由的實(shí)例
export default router
12.3?把router對象掛載到main.js上
(在new Vue中的router是“router:router”的簡寫,若import routerVue from 'xxxx',則應(yīng)寫為router:routerVue)
( "el"等價(jià)于$mount)
12.4 路由的基本使用
- 第一步:在index.js中定制路由規(guī)則:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Prize from '@/components/Prize.vue'
import Home from "@/components/Main.vue";
import parent from '@/components/parent'
Vue.use(VueRouter);
const router =new VueRouter({
routes:[
{
path:'/',
redirect:'/home'
},
{
path:'/home',
component:Home
},
{
path:'/prize',
component:Prize,
},
{
path:'/parent',
component:parent
}
]
})
export default router
- 第二步:在頁面中使用router-view:
<!--可以實(shí)現(xiàn)路由跳轉(zhuǎn),如下:-->
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 組件來導(dǎo)航. -->
<!-- 通過傳入 `to` 屬性指定鏈接. -->
<!-- <router-link> 默認(rèn)會被渲染成一個(gè) `<a>` 標(biāo)簽 -->
<router-link to="/home">首頁</router-link>
<router-link to="/prize">獎(jiǎng)品</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的組件將渲染在這里 -->
<router-view></router-view>
</div>
//也可以在methods中使用,如下:
methods: {
goBack() {
window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/')
}
}
- 在進(jìn)行模塊化導(dǎo)入的時(shí)候,如果給定的是文件夾,則默認(rèn)導(dǎo)入這個(gè)文件夾下,名字叫做 index.js 的文件
- 當(dāng)對應(yīng)的路由匹配成功,將自動設(shè)置 class 屬性值 。查看API文檔學(xué)習(xí)更多相關(guān)內(nèi)容。??????
12.5??路由重定向
12.6?嵌套路由
需求:在apptest.vue下路由到about,在about組件下路由到tab1、tab2
- 第一步:路由配置index.js
{
path: '/about',
component: About,
// redirect: '/about/tab1',
children: [
// 子路由規(guī)則
// 默認(rèn)子路由:如果 children 數(shù)組中,某個(gè)路由規(guī)則的 path 值為空字符串,則這條路由規(guī)則,叫做“默認(rèn)子路由”
{ path: '', component: Tab1 },
{ path: 'tab2', component: Tab2 }
]
},
- 第二步:在apptest.vue下路由到about
<router-link to="/about">關(guān)于</router-link>
<!-- 作用很單純:占位符,給要顯示的組件預(yù)留位置的 -->
<router-view></router-view>
- 第三步:在about組件下路由到tab1、tab2
<router-link to="/about">關(guān)于</router-link>
<router-link to="/about/tab2">關(guān)于</router-link>
<router-view></router-view>
12.7?動態(tài)路由匹配
需求:有一個(gè)組件,對于所有 ID 各不相同的用戶,都要使用這個(gè)組件來渲染。
const User = {
template: '<div>User</div>'
}
const router = new VueRouter({
routes: [
// 動態(tài)路徑參數(shù) 以冒號開頭
{ path: '/user/:id', component: User }
//相當(dāng)于/user?id=xxx
]
})
?①可以通過const User = {template: '{{ $route.params.動態(tài)路徑參數(shù) }}'來查看當(dāng)前用戶的動態(tài)路徑參數(shù)。
打印this時(shí)是對象
?this.$route 是路由的“參數(shù)對象”
this.$router 是路由的“導(dǎo)航對象”
?②可以為路由規(guī)則開啟 props 傳參,從而方便的拿到動態(tài)參數(shù)的值
【index.js】
{ path: '/movie/:mid', component: Movie, props: true },
【movie.vue】
props: ['mid'],
- 在 hash 地址中, / 后面的參數(shù)項(xiàng),叫做“路徑參數(shù)”
- 在路由“參數(shù)對象”中,需要使用 this.$route.params 來訪問路徑參數(shù)
- 在 hash 地址中,? 后面的參數(shù)項(xiàng),叫做“查詢參數(shù)”
- 在路由“參數(shù)對象”中,需要使用 this.$route.query 來訪問查詢參數(shù)
- 在 this.$route 中,path 只是路徑部分;fullPath 是完整的地址
【 例如】:
/movie/2?name=zs&age=20 是 fullPath 的值
/movie/2 是 path 的值
12.8?捕獲所有路由或 404 Not found 路由
{
// 會匹配所有路徑
path: '*'
}
{
// 會匹配以 `/user-` 開頭的任意路徑
path: '/user-*'
}
注:當(dāng)使用通配符路由時(shí),請確保路由的順序是正確的,也就是說含有通配符的路由應(yīng)該放在最后。路由?{ path: '*' }?通常用于客戶端 404 錯(cuò)誤。
12.9?編程式導(dǎo)航跳轉(zhuǎn)
vue-router中的編程式導(dǎo)航API,常用的導(dǎo)航API有:
①this.$router.push('hash地址')
跳轉(zhuǎn)到指定hash地址,并增加一條歷史記錄
②this.$router.replace('hash地址')
跳轉(zhuǎn)到指定的hash地址,并替換掉當(dāng)前的歷史記錄
③this.$router.go(數(shù)值n)
跳回第n條歷史記錄?
<template>
<div class="movie-container">
<button @click="gotoLk">通過 push 跳轉(zhuǎn)到“洛基”頁面</button>
<button @click="gotoLk2">通過 replace 跳轉(zhuǎn)到“洛基”頁面</button>
<button @click="goback">后退</button>
<!-- 在行內(nèi)使用編程式導(dǎo)航跳轉(zhuǎn)的時(shí)候,this 必須要省略,否則會報(bào)錯(cuò)! -->
<button @click="$router.back()">back 后退</button>
<button @click="$router.forward()">forward 前進(jìn)</button>
</div>
</template>
<script>
export default {
name: 'Movie',
methods: {
gotoLk() {
// 通過編程式導(dǎo)航 API,導(dǎo)航跳轉(zhuǎn)到指定的頁面
this.$router.push('/movie/1')
},
gotoLk2() {
this.$router.replace('/movie/1')
},
goback() {
// go(-1) 表示后退一層
// 如果后退的層數(shù)超過上限,則原地不動
this.$router.go(-1)
}
}
}
</script>
12.10?路由守衛(wèi)
路由守衛(wèi)可以控制路由的訪問權(quán)限。
12.10.1 全局前置守衛(wèi)
【index.js】中
// 為 router 實(shí)例對象,聲明全局前置導(dǎo)航守衛(wèi)
// 只要發(fā)生了路由的跳轉(zhuǎn),必然會觸發(fā) beforeEach 指定的 function 回調(diào)函數(shù)
router.beforeEach(function(to, from, next) {
// to 表示將要訪問的路由的信息對象
// from 表示將要離開的路由的信息對象
// next() 函數(shù)表示放行的意思
// 分析:
// 1. 要拿到用戶將要訪問的 hash 地址
// 2. 判斷 hash 地址是否等于 /main。
// 2.1 如果等于 /main,證明需要登錄之后,才能訪問成功
// 2.2 如果不等于 /main,則不需要登錄,直接放行 next()
// 3. 如果訪問的地址是 /main。則需要讀取 localStorage 中的 token 值
// 3.1 如果有 token,則放行
// 3.2 如果沒有 token,則強(qiáng)制跳轉(zhuǎn)到 /login 登錄頁
if (to.path === '/main') {
// 要訪問后臺主頁,需要判斷是否有 token
const token = localStorage.getItem('token')
if (token) {
next()//如果有token(登錄)就放行
} else {
// 沒有登錄,強(qiáng)制跳轉(zhuǎn)到登錄頁
next('/login')
}
} else {
next()
}
})
12.10.2 next 函數(shù)的 3 種調(diào)用方式
12.10.3?關(guān)于path和fullpath
如:http://localhost:8080/index?page=1
fullPath:路由全地址,fullPath為/index?page=1
path:路徑,不帶參數(shù),path為/index
12.11 路由傳參
12.11.1?query傳參
1. 路由跳轉(zhuǎn)并攜帶query參數(shù),to的字符串寫法 messageData是一個(gè)變量
<router-link :to="`/home/news?id=001&message=${messageData}`" ></router-link>
2. 路由跳轉(zhuǎn)并攜帶query參數(shù),to的對象
<router-link :to="{
path:"/home/news",
query:{
id:001,
message:messageData
}
}" >
</router-link>
獲取參數(shù):this.$route.query.id 、 this.$route.query.message?
12.11.2 params傳參
?方式一:路由跳轉(zhuǎn)并攜帶param參數(shù),to的字符串寫法 ,首先我們要在路由文件中定義我們要傳遞的參數(shù)
// 1. 路由跳轉(zhuǎn)并攜帶params參數(shù),to的字符串寫法 messageData是一個(gè)變量
<router-link :to="`/home/news/001/${messageData}`" ></router-link> //即{id:001,message:xxx}
跳轉(zhuǎn)時(shí)直接斜杠/后面拼接參數(shù)
// 1. 路由跳轉(zhuǎn)并攜帶params參數(shù),to的字符串寫法 messageData是一個(gè)變量
<router-link :to="`/home/news/001/${messageData}`" ></router-link> //即{id:001,message:xxx}
方式二:路由跳轉(zhuǎn)并攜帶params參數(shù),to的對象寫法,不需要在路由文件中定義參數(shù)
<router-link :to="{
name:"HomeNews", //使用params傳參時(shí),必須使用name屬性進(jìn)行路由跳轉(zhuǎn),不能使用path配置項(xiàng)跳轉(zhuǎn)
params:{
id:001,
message:messageData
}
}" ></router-link>
獲取參數(shù):this.$route.params.id 、 this.$route.params.message
12.11.3?路由props配置
傳參配置: src/router/index.js
{
name:'HomeNews'
path:'news/:id/:message',//二級路由,定義參數(shù),表示第一個(gè)參數(shù)是id,第二個(gè)是message
component:News,
// 第一種寫法:props值為對象,該對象中所有的key-value最終都會通過props傳遞給組件news
// props:{a:1},
// 第二種寫法(只能params):props值為Boolean,為true時(shí)把路由收到的`params`參數(shù)通過props傳遞給組件news
// props:true,
// 第三種寫法:props值為函數(shù),該函數(shù)返回的對象中每一組key-value都會通過props傳遞給組件news
props:function(route){
return {
id:route.query.id,
message:route.query.message
}
},
},
使用: New.vue
export default{
prors:['id','message']
}
13?狀態(tài)管理
13.1 狀態(tài)管理簡介
vuex是專為vue.js應(yīng)用程序開發(fā)的狀態(tài)管理模式。它采用集中存儲管理應(yīng)用的所有組件的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化。vuex也集成刀vue的官方調(diào)試工具devtools extension,提供了諸如零配置的time-travel調(diào)試、狀態(tài)快照導(dǎo)入導(dǎo)出等高級調(diào)試功能。
13.2 Vuex 的思想
當(dāng)我們在頁面上點(diǎn)擊一個(gè)按鈕,它會觸發(fā)(dispatch)一個(gè)action, action 隨后會執(zhí)行(commit)一個(gè)mutation, mutation 立即會改變state, state 改變以后,我們的頁面會state 獲取數(shù)據(jù),頁面發(fā)生了變化。
13.3 核心狀態(tài)管理
通俗理解是存儲在store里的都是全局變量,可以通過方法提交更新,其他頁面和組件也會同步更新,拿到最新的值。狀態(tài)管理核心狀態(tài)管理有5個(gè)核心,分別是state、getter、mutation、action以及module。
- state
驅(qū)動應(yīng)用的數(shù)據(jù)源。state為單一狀態(tài)樹,可以使用一個(gè)對象包含全部的應(yīng)用層級狀態(tài),state就是數(shù)據(jù)源。
- getter
getter有點(diǎn)類似vue的計(jì)算屬性computed,當(dāng)我們需要對數(shù)據(jù)進(jìn)行處理,那么我們就需要使用getter,getter會接收state作為第一個(gè)參數(shù),而且getter的返回值會根據(jù)它的依賴被緩存起來,只有g(shù)etter中的依賴值(state中的某個(gè)需要派生狀態(tài)的值)發(fā)生改變的時(shí)候才會被重新計(jì)算。
const getters = {
getUserState (state) {
let data;
if(state.userState==0){
data='無效'
}else if(state.userState==1){
data = '1級'
}else{
data = '2級'
}
return data;
}
}
export default new Vuex.Store({
state,
mutations,
getters
})
頁面上使用這個(gè)getters:
計(jì)算數(shù)據(jù)狀態(tài):{{$store.getters.getUserState}}
- mutation
更改store中state狀態(tài)的唯一方法就是提交mutation,類似vue中的methods。每個(gè)mutation都有一個(gè)字符串類型的事件類型和一個(gè)回調(diào)函數(shù),我們需要改變state的值就要在回調(diào)函數(shù)中改變。我們要執(zhí)行這個(gè)回調(diào)函數(shù),那么我們需要執(zhí)行一個(gè)相應(yīng)的調(diào)用方法:store.commit。
- action
響應(yīng)在 view 上的用戶輸入導(dǎo)致的狀態(tài)變化。action可以提交mutation,在action中可以執(zhí)行store.commit,而且action中可以有任何的異步操作。action處理異步操作,由于mutation都是同步事務(wù),在 mutation 中混合異步調(diào)用會導(dǎo)致你的程序很難調(diào)試。action 類似于 mutation,不同在于:Action 提交的是 mutation,而不是直接變更狀態(tài)。
mutations: {
addAge: (state, payload) => {
state.informations.forEach(info => {
info.age += payload;
})
}
},
actions: {
addAge: (context, payload) => {
setTimeout(function () {
context.commit("addAge", payload);
}, 2000);
}
}
在組件的methods中能夠通過【this.$store.dispatch("addAge", 2);】分發(fā)action。
(或者使用mapActions輔助函數(shù)將組件的 methods 映射為 store.dispatch 調(diào)用)
methods: {
addAge() {
this.$store.dispatch("addAge", 2);
}
},
注意:
1、所有 store 中 state 的變更,都放置在 store 自身的 action 中去管理。
2、Vuex 的狀態(tài)存儲是響應(yīng)式的。當(dāng) Vue 組件從 store 中讀取狀態(tài)的時(shí)候,若 store 中的狀態(tài)發(fā)生變化,那么相應(yīng)的組件也會相應(yīng)地得到更新。
3、不能直接改變 store 中的狀態(tài)。改變 store 中的狀態(tài)的唯一途徑就是顯式地提交(commit)mutation。
13.4 在項(xiàng)目中使用
13.4.1 store一般有以下6個(gè)文件
13.4.2?vuex中 this.$store.dispatch() 與 this.$store.commit()方法的區(qū)別
這兩個(gè)的區(qū)別是存取的方式不同,兩個(gè)都是傳值給vuex的mutation改變state.
- this.$store.dispatch含有異步操作,可以向后臺提交數(shù)據(jù)
【存儲】this.$store.dispatch("action的方法名",value)
【取值】this.$store.getters.action的方法名
- this.$store.commit同步操作
【存儲】this.$store.commit("mutation的方法名",value)
【取值】this.$store.state.mutation的方法名
13.4.3 實(shí)例1
在app.vue里先import store from “./store” 并且在new vue實(shí)例的時(shí)候加上store,這樣就可以全局調(diào)用了。
【src/store/index.js】引入Vuex文組件:
//第一步:使用import引入vue和vuex
import Vue from 'vue';
import Vuex from 'vuex';
//第二步:把vuex作為組件引入
Vue.use(Vuex);
//第三步:實(shí)例化vuex.store對象
//store變量是實(shí)例化一個(gè)vuex.store
export const store =new Vuex.Store({
//第四步:定義state
//state專門用于保存共享的狀態(tài)值
state:{
//保存登陸狀態(tài)
login:false
},
//第五步:編寫方法改變state中的值
//專門書寫方法,用于更新state中的值
mutations:{
doLogin(state){
state.login=true;
},
doLoginout(state){
state.login=false;
}
}
});
【 src/components/Header.vue】組件JS部分:
<script>
//使用vuex的mapState需要引入
import {mapState} form "vuex";
export default{
name:"Header",
//引入vuex>store>state中的值,必須在計(jì)算屬性中書寫
computed:{
//mapState輔助函數(shù),可以快速引入store中的值
...mapState(["login"])
},
methods:{
loginout(){
//調(diào)用store里登出的方法
this.$store.commit(" doLoginout");
}
}
}
</script>
【src/components/Login.vue】組件JS部分 :
<script>
export default {
name: "Login",
data() {
return {
};
},
methods: {
doLogin() {
……
// 路由跳轉(zhuǎn)指定頁面
this.$router.push({ path: "/" });
//更新 vuex 的 state的值, 必須通過 mutations 提供的方法才可以
//通過 commit('方法名') 就可以觸發(fā)mutations 中的指定方法
this.$store.commit("doLogin");
}
});
}
}
};
</script>
使用$router.push轉(zhuǎn)到首頁url,并且調(diào)用store里的登錄方法把共享登錄狀態(tài)變成true。
13.4.4 實(shí)例2
【聲明】src/store/index.js:
import Vuex from 'vuex';
import Vue from 'vue';
……;
import test from '@/store/modules/test'
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
……,
test
},
});
【定義】src/store/models/test.js:文章來源:http://www.zghlxwxcb.cn/news/detail-616919.html
const state={
username:'lanchun',
userState:0
}
const mutations={
SetUserName(state,name){
state.username=name;
},
SetUserState(state,num){
state.userState+=num;
}
}
export default{
state,
mutations
}
【使用】src/views/page.vue:文章來源地址http://www.zghlxwxcb.cn/news/detail-616919.html
<template>
<div>
<h1>{{$store.state.test.username}}</h1>
<h1>{{$store.state.test.userState}}</h1>
數(shù)據(jù)狀態(tài):
<a-button @click="addState">狀態(tài)+1</a-button>
</div>
</template>
methods: {
addState(){
console.log(this.$store.state.test);
console.log(this.$store);
this.$store.commit('SetUserName','張三');
this.$store.commit('SetUserState',1);
},
}
到了這里,關(guān)于Vue知識點(diǎn)匯總【持更】的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!