我们使用的是Vue.js,如果你问我,这是一个非常好的框架。从Knockout.js和WPF我知道可以为绑定指定上下文。如何使用Vue.js做到这一点呢?
请参见下面的示例。这里的binding-context是我在Vue中寻找的功能的伪代码。
Vue.component('hosting-setup', {
template:
'<wizard>' +
'<wizard-step binding-context="step1" :title="title">' +
'<select :options="choices"></select>' +
'</wizard-step>' +
'<wizard-step binding-context="step2" :title="title">' +
'<select :options="choices"></select>' +
'</wizard-step>' +
'</wizard>',
data: function () {
return {
step1: {
title: 'Choose virtualization software',
choices: ['Virtual Box', 'VMWare'],
choice: undefined,
},
step2: {
title: 'Choose guest operating system',
choices: ['Debian 6', 'Ubuntu 16', 'Windows Server 2012'],
choice: undefined
}
};
}
});发布于 2017-10-30 22:10:19
在Vue中没有"with“绑定的等价物。对于您想要做的事情,有几种方法,但对于您的示例,我将使用computed将数据作为数组返回,然后使用v-for打印出每个组件,并将相关数据作为道具进行传递:
Vue实例
Vue.component('wizard-step', {
template: `<div>{{title}}</div>`,
props: ['title']
});
new Vue({
el: '#app',
computed: {
wizardSteps() {
return [this.step1, this.Step2]
}
},
data() {
return {
step1: {
title: 'Choose virtualization software',
choices: ['Virtual Box', 'VMWare'],
choice: undefined,
},
Step2: {
title: 'Choose guest operating system',
choices: ['Debian 6', 'Ubuntu 16', 'Windows Server 2012'],
choice: undefined
}
};
}
})标记
<wizard-step :title="step.title" v-for="(step, index) in wizardSteps" :key="index"></wizard-step>这是JSFiddle:http://jsfiddle.net/craig_h_411/vzq25go5/
编辑
如果您希望将数据直接向下传递给组件,则可以使用v-bind传递对象,并将要在组件中使用的对象属性名称声明为props,这可能更接近您的要求,因此:
Vue.component('wizard-step', {
template: `<div>
{{title}}
<select>
<option v-for="choice in choices" >{{choice}}</option>
</select>
</div>`,
props: ['title','choices']
});父标记
<wizard-step v-bind="step1"></wizard-step>
<wizard-step v-bind="Step2"></wizard-step>这是它的JSFiddle:http://jsfiddle.net/craig_h_411/7dg41j0w/
发布于 2018-09-09 16:42:09
如果你真的嵌套了孩子,可以试着用v-for来作弊,只有一个项目数组。
<template v-for="local in [data.nest1.nest2.nest3]">
//normal binding using local.XXXX
</template>发布于 2020-02-13 06:17:44
在Vue 2.6.10中测试:
<template>
<wizard>
<wizard-step v-if="props.step1 ? step = props.step1 : false" :title="step.title">
<select :options="step.choices"></select>
</wizard-step>
<wizard-step v-if="props.step2 ? step = props.step2 : false" :title="step.title">
<select :options="step.choices"></select>
</wizard-step>
</wizard>
</template>注意:更好的是,对于更简洁的代码,您可以创建一个仅用于传递标题和选项的子组件:
也就是说。
<template>
<wizard>
<wizard-step v-if="props.step1" :step="props.step1" />
<wizard-step v-if="props.step2" :step="props.step2" />
</wizard>
</template>您的子向导步骤为:
<template>
<wizard-step :title="step.title">
<select :options="step.choices"></select>
</wizard-step>
</template>另一个改进是,如果您能够控制返回的数据的结构,则可以返回一个steps数组(而不是step1和step2),并且可以使用for-each进一步简化:
<template>
<wizard>
<wizard-step v-for="step in props.data" :step="step" />
</wizard>
</template>https://stackoverflow.com/questions/47016786
复制相似问题