[英]How can I specify a binding context in Vue.js just like in knockout.js and WPF
如果你问我,我们正在使用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
}
};
}
});
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/
如果你真的有嵌套的孩子,可以尝试使用 v-for 和 1 个项目数组作弊。
<template v-for="local in [data.nest1.nest2.nest3]">
//normal binding using local.XXXX
</template>
在 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>
注意:更好的是,为了更简洁的代码,您可以创建一个子组件并传递标题和选项:
IE
<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
(而不是步骤 1 和步骤 2),并且您可以使用 for-each 进一步简化:
<template>
<wizard>
<wizard-step v-for="step in props.data" :step="step" />
</wizard>
</template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.