- 使用set方法动态添加对象属性值
this.$set(this.creatorLevels, item.value, item.description);
- vue中关于bus的理解和用处
a. 将Bus单独抽离成一个文件,后在需要的页面引入
import Vue from 'vue';
let Bus = new Vue();
export default Bus;
b. 用于兄弟之间传值
兄弟组件1:
mounted() {
Bus.$on('log', val => {
console.log(val);
})
}
兄弟组件2:
<button @click="tabBus"></button>
methods: {
tabBus() {
Bus.$emit('log',120);
}
}
- 鉴于上面提到了组件之间传值,顺便介绍父子组件传值.
父组件:
<upLoad :data="data"></upLoad>
子组件:
props: {
data: {
default: false,
type: Boolean
}
}
父组件:
<button @show="showFather"></button>
methods: {
showFather(a,b) {
console.log(a, b);
}
}
子组件:
<button @click="sonClick"><button/>
methods: {
sonClick() {
this.$emit('show',this.message,this.info);
}
}
- Vue .sync修饰符与this.$emit(update:xxx)
但我们常常会遇到需要在子组件中修改父组件数据的场景。.sync修饰符就可以帮助我们实现这种功能
a. 不使用.sync修饰符的写法
父组件代码:
<bz-detail :is-show="detailVisible" @update:isShow="func"></bz-detail>
methods: {
func(val) {
this.detailVisible = val;
}
}
子组件中的方法
onClose() {
this.$emit('update:isShow',false);
}
注意:this.$emit()中update后的字段要与父组件中保持一致
--------------------------------------
b. 使用.sync修饰符的写法
父组件代码:
<bz-detail :is-show.sync="detailVisible"></bz-detail>
子组件代码:
onClose () {
this.$emit('update:isShow', false)
this.$emit('update:is-show', false)
}
注意:使用sync修饰符与 $emit(update:xxx)时 ,驼峰法 和 -写法都可以,而且也不需要与父组件保持一致。