关于那些年我遇到的vue相关问题

127 阅读1分钟
  1. 使用set方法动态添加对象属性值
this.$set(this.creatorLevels, item.value, item.description);// 对象名,该对象属性,该对象该属性值
  1. vue中关于bus的理解和用处
// 用法和步骤
a. 将Bus单独抽离成一个文件,后在需要的页面引入
    import Vue from 'vue';
    let Bus = new Vue();
    export default Bus;
b. 用于兄弟之间传值
兄弟组件1:
mounted() {
    // 给兄弟组件绑定一个log事件,等待触发
    Bus.$on('log', val => {
        console.log(val);
    })
}
兄弟组件2:
<button @click="tabBus"></button>
methods: {
    tabBus() {
        // 点击按钮触发log事件,然后传值过去
        Bus.$emit('log',120);
    }
}
  1. 鉴于上面提到了组件之间传值,顺便介绍父子组件传值.
// 父组件传递给子组件
父组件:
<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);
    }
}
  1. Vue .sync修饰符与this.$emit(update:xxx)
// 描述:Vue中的数据是单向数据流:父级 prop 的更新会向下流动到子组件中,但是反过来则不行,即子组件无法直接修改父组件中的数据。
但我们常常会遇到需要在子组件中修改父组件数据的场景。.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)时 ,驼峰法 和 -写法都可以,而且也不需要与父组件保持一致。