In my application i have a component and i want wath his properties outside of the component. I've created this example:
Vue.component('vue-table', {
template: '<div><template v-for="row in apiData.content"><span>{{row.name}}</span><button @click="remove(row)">remove</button><br></template></div>',
data: function() {
return {
//this data will be loaded from api
apiData: {
total: 20,
content: [
{id: 10, name: 'Test'},
{id: 12, name: 'John'},
{id: 13, name: 'David'},
],
},
};
},
methods: {
remove(row) {
this.apiData.content.splice(this.apiData.content.indexOf(row), 1);
},
},
})
new Vue({
el: '#app',
methods: {
isActive(){
//how can i check if in vue-table apiData.content > 0?
//return this.$refs.table.apiData.data.length > 0;
},
},
})
http://jsfiddle.net/z11fe07p/2806/
So i want to change class of span to 'active' when the length of vue-table apiData.content.length > 0
How can i do this?
The standard practice would be to emit an event in the child and have the parent receive and act on it. You might wonder whether you can watch the length of an array -- one that doesn't even exist when the component is instantiated -- and the answer is yes.
Look at the watch section. IMO, this is so cool that it's probably frowned upon.
Vue.component('vue-table', {
template: '<div><template v-for="row in apiData.content"><span>{{row.name}}</span><button @click="remove(row)">remove</button><br></template></div>',
data: function() {
return {
//this data will be loaded from api
apiData: {},
};
},
methods: {
remove(row) {
this.apiData.content.splice(this.apiData.content.indexOf(row), 1);
},
},
watch: {
'apiData.content.length': function(is, was) {
this.$emit('content-length', is);
}
},
created() {
this.apiData = {
total: 20,
content: [{
id: 10,
name: 'Test'
}, {
id: 12,
name: 'John'
}, {
id: 13,
name: 'David'
}, ],
};
}
})
new Vue({
el: '#app',
data: {
isActive: false
},
methods: {
setActive(contentLength) {
this.isActive = contentLength > 0;
}
},
})
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.active {
font-weight: bold;
}
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
<p>
<span :class="{active: isActive}">Users:</span>
</p>
<vue-table refs="table" @content-length="setActive"></vue-table>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With