我想更改图像,然后触发图像更新。
例如 http://jsbin.com/kuluyike/3/edit?html,js,output
<div id="colorPicker">
<img v-attr="src:color" alt="{{color}}">
<ul>
<li v-repeat="colors">
<label>
<input type="radio" id="{{name}}" name="color" v-model="color" value="{{image}}">
{{name}}
</label>
</li>
</ul>
</div>
var cp = new Vue({
el: '#colorPicker',
data: {
colors: [
{
name: 'red',
image: 'red.jpg'
},
{
name: 'pink',
image: 'pink.jpg'
},
{
name: 'blue',
image: 'blue.jpg'
}
]
}
});
但这不适用于Vue.js 2.x版
如何更改代码,以便基于2.x版本工作
答案 0 :(得分:3)
在Vue 2.0, the syntax has changed for attributes中,这意味着您现在必须声明以下属性:
<img :src="color" :alt="color">
<input type="radio" :id="name" :name="color" v-model="color" :value="image">
在Vue 2.0, the syntax for loops has changed from v-repeat
to v-for
:中:
<li v-for="(colorInfo, index) in colors">
<input type="radio" :id="colorInfo.name" name="color" v-model="color" :value="colorInfo.image">
在Vue 2.0开发模式下,访问未声明的属性时会发出警告
data: {
// ...
color: undefined,
},
var cp = new Vue({
el: '#colorPicker',
data: {
color: undefined,
colors: [
{
name: 'red',
image: 'red.jpg'
},
{
name: 'pink',
image: 'pink.jpg'
},
{
name: 'blue',
image: 'blue.jpg'
}
]
}
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="colorPicker">
<img :src="color" :alt="color">
<ul>
<li v-for="(colorInfo, index) in colors">
<label>
<input type="radio" :id="colorInfo.name" name="color" v-model="color" :value="colorInfo.image">
{{colorInfo.name}}
</label>
</li>
</ul>
</div>
答案 1 :(得分:2)
您可以在此处使用v-for
在Vue 2.x中进行循环,例如:
new Vue({
el: '#colorPicker',
data: {
color: null,
colors: [{
name: 'red',
image: 'red.jpg'
},
{
name: 'pink',
image: 'pink.jpg'
},
{
name: 'blue',
image: 'blue.jpg'
}
]
}
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="colorPicker">
<img :src="color" :alt="color" v-if="color" />
<ul>
<li v-for="c in colors">
<label>
<input type="radio" name="color" v-model="color" :value="c.image"/>
{{c.name}}
</label>
</li>
</ul>
<p v-if="color"><b>Selected image name: </b> {{color}}</p>
</div>