问题
I am trying to change the font-size of text through a dropdown and for the most part it is working like i wanted. Although, is there a better way to do it like using a computed or watcher? Not sure how i would execute that?
this is a working pen: https://codepen.io/anon/pen/xoMXPB?editors=1011 How can i change logic on line 6 to replace it with a computed or watcher?
<div id="app">
<v-app id="inspire">
<v-container>
<v-select :items="items" label="Font-Size" v-model="myFont">
</v-select>
<div>
<p :style="{'font-size': myFont == 'Large' ? 24 + 'px' : myFont ==
'Medium' ? 18 + 'px' : 14 + 'px'}">Large="24px", Small="16px",
Medium="18px"</p>
</div>
</v-container>
</v-app>
</div>
new Vue({
el: '#app',
data() {
return {
items: [
'Large',
'Medium',
'Small',
],
myFont: null,
};
},
})
Any help is appreciated.
回答1:
As you say, a computed property (or in this case a method) could help you here - largely just condensing the code and making it a little more flexible;
methods: {
calculateFontSize: function(size){
switch(size){
case "LARGE":
return "24px";
case "MEDIUM":
return "18px";
default:
return "14px";
}
}
}
<p :style="calculateFontSize(myFont)"></p>
回答2:
What about using an array of objects as your options to simplify the conditional in the computed property.
Note the item-text
and item-value
props in the v-select. Then the conditional can be used to simply add the style syntax font-size: ${this.myFont}px
Vue.config.silent = true;
Vue.use(Vuetify);
new Vue({
el: '#app',
data: () => ({
items: [
{ label: 'Large', value: 24 },
{ label: 'Medium', value: 18 },
{ label: 'Small', value: 16 },
],
myFont: 16
}),
computed: {
style() {
return `font-size: ${this.myFont}px` ;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.18/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css">
<div id="app">
<v-app id="inspire">
<v-container>
<v-select :items="items" item-text="label" item-value="value" label="Font-Size" v-model="myFont"></v-select>
<div>
<p :style="style">Font is {{myFont}}px</p>
</div>
</v-container>
</v-app>
</div>
来源:https://stackoverflow.com/questions/56974905/creating-a-computed-property