|
|
1
tao
5 年前
决定的依据是
Colors
将在组件的整个生命周期中发生更改。如果它不会更改,只需使用计算属性:
Vue.config.devtools = false;
Vue.config.productionTip = false;
const Colors = {
GREEN: '#0F0',
};
Vue.component('ExampleComponent', {
name: 'ExampleComponent',
template: `
<div>
Value: <span style="color:${Colors.GREEN}">{{ Colors.GREEN }}</span>
</div>
`,
computed: {
Colors: () => Colors
}
})
new Vue({
el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<example-component />
</div>
如果您计划更改它(基于用户交互或脚本),请将其放入
data()
:
Vue.config.devtools = false;
Vue.config.productionTip = false;
const Colors = {
GREEN: '#0F0',
};
Vue.component('ExampleComponent', {
name: 'ExampleComponent',
template: `
<div>
Value: <span :style="{color: Colors.GREEN}">{{ Colors.GREEN }}</span>
<button @click="changeColors">Change Colors</button>
</div>
`,
data: () => ({
Colors
}),
methods: {
changeColors() {
this.Colors = {
GREEN: 'red'
}
}
}
})
new Vue({
el: '#app',
})
<script src=“https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js”></script>
<div id=“app”>
<示例组件/>
</分区>
如果要允许用户选择一个可用的颜色选项,则意味着
颜色
内容不会改变,因此您将使用
颜色
,以及
数据()
对于当前选定的颜色:
Vue.config.devtools = false;
Vue.config.productionTip = false;
const Colors = {
GREEN: '#090',
RED: '#C00',
BLUE: '#009',
ORANGE: '#F90'
};
Vue.component('ExampleComponent', {
name: 'ExampleComponent',
template: `
<div> Value:
<span
:style="{color: currentColor, fontWeight: 'bold'}"
v-text="currentColor" />
<select v-model="currentColor">
<option
v-for="(color, key) of Colors"
v-text="\`\${key}: \${color}\`"
:key="key"
:value="color" />
</select>
</div>
`,
data: () => ({
currentColor: Colors.GREEN
}),
computed: {
Colors: () => Colors
},
methods: {
setColor(color) {
this.currentColor = color;
}
}
})
new Vue({
el: '#app',
})
<script src=“https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js”></script>
<div id=“app”>
<示例组件/>
</分区>
你用复选框更新了你的问题。因此,我添加了一个使用复选框和收音机的示例,具体取决于用户可能需要什么:
Vue.config.devtools = false;
Vue.config.productionTip = false;
const Colors = {
GREEN: '#090',
RED: '#C00',
BLUE: '#009',
ORANGE: '#F90'
};
Vue.component('ExampleComponent', {
name: 'ExampleComponent',
template: `
<div> checkedColors:
<label v-for="(color, key) of Colors"
:key="key">
<input name="color"
type="checkbox"
:value="color"
v-model="checkedArray">
<span v-text="color" :style="{color}" />
</label>
<hr>
pickedColor:
<label v-for="(color, key) of Colors"
:key="color">
<input name="picked"
type="radio"
:value="color"
v-model="picked">
<span v-text="color" :style="{color}" />
</label>
<hr>
<pre>checkedArray: {{ stringify(checkedArray) }}</pre>
<pre>picked: {{ picked }}</pre>
</div>
`,
data: () => ({
checkedArray: [],
picked: Colors.GREEN
}),
computed: {
Colors: () => Colors
},
methods: {
stringify(value) {
return JSON.stringify(value, true, 2);
}
}
})
new Vue({
el: '#app',
})
<script src=“https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js”></script>
<div id=“app”>
<示例组件/>
</分区>
|