Hello!大家好今天給大家講一下我最近瞭解到的一些新的東西在這裏給大家分享一下。
一:.sync
官方推薦使用一種update:my-prop-name 的模式來替代事件觸發,目的是爲了優雅而不粗魯的實現父子組件間的雙向綁定!先來完成一個小功能:通過父組件按鈕將子組件顯示出來。
父組件代碼(通常的做法):
<template>
<div>
<button @click="show = true">我是父組件的按鈕</button>
<coment-children v-if="show" @isShow="isShow"></coment-children>
</div>
</template>
<script>
import comentChildren from "./children";
export default {
data() {
return {
show: false
};
},
components: {
comentChildren
},
methods:{
isShow(val){this.show = val;}
}
};
</script>
子組件child代碼:
<template>
<div style="width:200px;height:200px;background:red;">
我是helloWorld模塊的子組件
<button @click="isShow">我是子組件的按鈕點我隱身</button> //第一種
<button @click="$parent.show = false">我是子組件的按鈕點我隱身</button> //第二種(不推薦也不規範)
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
isShow() {
this.$emit("isShow", false);
}
}
};
</script>
然後咱們改一種方法看看能不能正常運行
父組件: <coment-children @update:isShow="show" v-if="show"/></coment-children>
子組件的emit自然也要做對應調整:
this.$emit("update:isShow",false);
一切運行正常不報錯,咱們最後改成.sync的方法
父組件:<template>
<div>
<button @click="show = true">我是父組件的按鈕</button>
<coment-children v-if="show" :isShow.sync="show"></coment-children>
</div>
</template>
<script>
import comentChildren from "./children";
export default {
data() {
return {
show: false
};
},
components: {
comentChildren
}
};
</script>
子組件:<template>
<div style="width:200px;height:200px;background:red;">
我是helloWorld模塊的子組件
<button @click="$emit('update:isShow',false)">我是子組件的按鈕點我隱身</button>
</div>
</template>
<script>
export default {
data() {
return {};
}
};
</script>
git地址:https://github.com/Liingot/sync.git
注意:.sync官方給出的解釋就是一種語法糖的意思
最後:sync只是給大傢伙提供了一種與父組件溝通的思路而已!所以在後面日子裏,你如果只是單純的在子組件當中修改父組件的某個數據時,建議使用sync,簡單,快捷,不需要在傳一個自定義方法來接收了,今天就到這裏謝謝大家。