通过Vue可观察为道具?

时间:2019-04-26 01:16:08

标签: vue.js observable

var state = Vue.observable({
    selectedTab: ''
});

Vue.component('block-ui-tab', {
    props: ['name', 'handle', 'icon'],
    template: '<li :handle="handle" :class="{ active: state.selectedTab === handle }"><i :class="icon"></i>{{ name }}</li>'
});

var app = new Vue({
    el: '#app',
    data: {},
    methods: {},
    computed: {},
    watch:{},
    mounted: function(){},
});

这不起作用,所以我想知道如何在组件和vue根实例中使用可观察对象?通过它作为道具,还是?

2 个答案:

答案 0 :(得分:0)

您可能想在数据选项中声明state(请参阅Declaring Reactive Properties)。然后,您可以将其传递给组件。

Vue.component('block-ui-tab', {
    props: ['name', 'handle', 'icon', 'state'],
    template: '<li :handle="handle" :class="{ active: state.selectedTab === handle }"><i :class="icon"></i>{{ name }}</li>'
});

var app = new Vue({
    el: '#app',
    data: {
        state: {
            selectedTab: '',
        }
    },
    methods: {},
    computed: {},
    watch:{},
    mounted: function(){},
});

答案 1 :(得分:0)

使用计算的属性有效:

 computed: {
   selectedTab: function() {
     return state.selectedTab
   }
 }