vuejs组件内的props的属性赋值问题?

组件:<test :loading.sync="loading"></test>

Vue.component('test',{
     template: '#testText',
     props: {
         loading: {
            type: Boolean,
            default: false
        }
     },
     methods: {
                getData: function (data) {
                    this.loading = false;//此句有错误,该如何更正
                }
            }
});

new Vue({
        el: '#indexBox',
        data: {
            loading : false
        },
        methods : {
                loadMore: function () {
                    this.loading = true;
                }
            }
    });

我想在子组件里面变更loading的值回传给父组件,请问该如何控制loading

阅读 11.7k
4 个回答

你用的是vue2吧,如果是vue2的话就应该用事件来把子组件的状态传给父组件,有两种办法,一种是在父组件中传一个v-model="outerLoading",然后子组件里面

watch:{
    outerLoading: {
        immediate: true,
        handler() {
            this.innerLoading = v
        }
    },
    innerLoading (v) {
        this.emit('input', v)
    }
}

这样outLoading就会响应innerLoading,实现双向绑定的功能。
还有一种做法和这个类似,就是把this.emit('input', v)换成this.emit('eventName', v),然后在父组件中@eventName="eventFunc", 再通过父组件中的eventFunc(v) { //code... }来响应子组件的状态

不建议用赋值的方式直接改变父组件的值,建议用$on、$emit链接描述

vue2 已经取消了.sync了吧~

推荐问题