Reputation: 229
I have to show the name prop as initials. It shows the initials fine on mount. but when I later change the value in the parent component. It doesn't change values. I tried computed as well but it shows that I didn't use the computed property. What am I missing here?
got this two errors
'computedInitial:' is defined but never used no-unused-labels
'get' is not defined
code
<template>
<div>
{{ showInitial }}
</div>
</template>
<script>
export default {
props: {
name: {
type: String,
},
data() {
return {
showInitial: null,
};
},
computed(){
computedInitial:{
get()
return this.name
}
},
mounted() {
let initials = this.computedInitial.match(/\b\w/g) || [];
this.showInitial = ((initials.shift() || "") + (initials.pop() || "")).toUpperCase();
},
};
Upvotes: 2
Views: 70
Reputation: 28414
There's a syntax error in the computed property. Also, you only need a computed
property to show the initials of the name
:
const comp = Vue.component('comp', {
template: '#myComp',
props: {
name: { type: String }
},
computed: {
computedInitial: {
get() {
let initials = this.name.match(/\b\w/g) || [];
return ((initials.shift() || "") + (initials.pop() || "")).toUpperCase();
}
}
},
mounted() {
this.$emit("set-name", "user test");
}
});
new Vue({
el: "#myApp",
data () {
return {
name: "test user"
}
},
methods: {
setName(newName) { this.name = newName; }
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="myApp">
<comp :name="name" @set-name="setName" />
</div>
<template id="myComp">
<div>
{{computedInitial}}
</div>
</template>
Upvotes: 1
Reputation: 1
your computed option should be like
computed:{
computedInitial:{
get(){
return this.name
}
}
}
But I recommend to define showInitial
as another computed property in order to be changed :
<template>
<div>
{{ showInitial }}
</div>
</template>
<script>
export default {
props: {
name: {
type: String,
},
data() {
return {
};
},
computed:{
computedInitial:{
get(){
return this.name
}
},
showInitial (){
let initials = this.computedInitial.match(/\b\w/g) || [];
return ((initials.shift() || "") + (initials.pop() || "")).toUpperCase()
}
},
};
Upvotes: 0