Vuex是什麼?
一般用於中大型項目,管理組件中的傳值方式,相當於angular中的全局服務,裏面有store聲明的屬性可以共享,每個組件都可以綁定。想要改變值,可以向store提交一個突變,方法便會執行一次。
父向子傳值
1、child子組件對desc屬性綁定的是sString,而sString的值是高漸離,故結果爲: 顯示父級傳過來的值:高漸離。
注意:子組件要接收父組件傳進來的值,那麼一定要放在props中.在props中聲明對應的屬性(舉例:desc),並進行屬性綁定,綁定對應的變量(舉例:sString)。
2、child子組件對students屬性綁定的是oStudent,而oStudent的job屬性爲”殺手”,故輸出的結果爲”2、(父向子傳值-對象方式)接收到父級傳過來的值:殺手”。
3、對input標籤進行雙向綁定到sValue,sValue已經在父組件中聲明.對szval進行監聽,當其值改變的時候,在輸入框輸入內容時,對應的函數console.log(newValue);執行,控制檯輸出改變後的值.而在組件中的鉤子函數created中,計時器改變其值爲”李斯”。
子組件調用父組件的方法
子組件中的button按鈕綁定點擊事件useParent(),該useParent()方法在子組件的methods中聲明,
在該方法中通過this.$parent.doParent(this.desc)調用父組件這個中的doParent()方法[功能console.log('父級中的方法',msg);],
而傳入的參數desc綁定了sString,child子組件對desc屬性綁定的是sString,而sString,的值是高漸離,因此:最終輸出的結果爲”父級中的方法 高漸離”。
代碼示例(參考上面的分析理解代碼)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>父向子通信</title>
<style type="text/css">
#app {
border: slateblue 1px solid;
width: 480px;
margin: auto;
padding: 20px;
border-radius: 5px;
background: #f2f2f2;
}
#wrapper {
border: 1px solid red;
width: 450px;
margin: auto;
padding: 10px;
border-radius: 5px;
background: #f9f9f9;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<div id="app">
<h1>該部分爲父組件</h1>
<h2>姓名:{{sString}}</h2>
<!-- 動態綁定 -->
<input type="text" v-model="sValue">
<!--v-bind:等價於:-->
<p>顯示父級傳入的值:{{oStudent.name}}</p>
<!-- 注意:desc,students,hou均爲子組件中props中聲明的屬性;sString,oStudent,sValue均爲父組件中聲明的變量 -->
<child :desc="sString" :students="oStudent" :hou="sValue"></child>
</div>
</body>
</html>
<template id="child">
<div id="wrapper">
<h1>該部分爲子組件</h1>
<!-- 注意:desc,students,hou均爲子組件中props中聲明的屬性 -->
<p>1、顯示父級傳過來的值:{{desc}}</p>
<p>2、(父向子傳值-對象方式)接收到父級傳過來的值:{{students.job}}</p>
<p>3、顯示父級中input標籤動態輸入的內容:{{hou}}</p>
<button @click="useParent">4、子組件調用父級中的方法</button>
</div>
</template>
<script>
// export default {};
let child = {
template: '#child',
data() {
return {};
},
methods: {
useParent() {
// 調用父級組件的方法
// $parent: 訪問父級組件的實例 $root: 訪問根實例 在本例中$parent與$root是一樣.
this.$parent.doParent(this.desc);
}
},
// 組件中的鉤子函數
// 1.created 當前組件實例創建好,但是頁面沒有顯示
created() {
setInterval(() => {
// 注意:父向子是單向數據流變化,在子組件中的變化,不會影響到父組件
this.hou = '李斯';
// 1.傳入的是引用,可以通過該對象改變屬性的值,會影響父級.
// this.students.name = '蓋聶';
// 2.傳入的是值,不會影響父級
this.students = {
name: '嬴政',
job:'皇帝'
};
}, 5000);
},
// 可以是數組, 但是不嚴謹, 建議使用對象
// 注意:父向子是單向數據流變化,在子組件中的變化,不會影響到父組件
// 值傳遞(簡單類型)/引用傳遞(array,object)
// 要想接收外部傳進來的值,那麼一定要放在props中
props: {
// 注意:寫屬性名的時候,建議不要寫成駝峯命名法.寫成駝峯命名時,在父級中調用需要寫成小寫-小寫的形式.
hou: {
type: String
},
desc: {
type: String,
// default是可選的
default: '自己設置的默認值',
required: true
},
students: {
type: Object,
// 設置對象的默認值,需要使用工廠函數,返回默認值。
default: function () {
return {
name: '韓非',
age: 20
};
}
}
}
};
new Vue({
el: '#app',
components: {
child
},
data: {
sString: '高漸離',
oStudent: {
name: '衛莊',
job:'殺手'
},
sValue: ''
},
watch: {
sValue: function (newValue, oldValue) {
console.log(newValue);
}
},
methods: {
doParent(msg) {
console.log('父級中的方法', msg);
}
}
});
</script>
效果圖