Vue使用render函数渲染动态模板时如何传递prop并正确同步v-model
Vue2 render函数渲染动态模板时v-model透传解决方案
原有代码存在的问题
- CustomSelect组件未正确实现v-model双向绑定逻辑:直接修改props传入的value会触发Vue单向数据流警告,也没有向上触发input事件通知父组件更新数据
- CustomSelect的option标签语法错误:错误将遍历逻辑写在
:value属性中,未使用v-for指令遍历选项列表 - DynamicTemplateComponent的render函数未将外层传入的props传递给内部动态组件,也没有监听内部组件的更新事件向上透传,导致根组件的v-model无法感知数据变化
- CustomSelect模板的闭合标签书写错误,多写了一个
<select>起始标签
修正后完整代码
JS逻辑代码
const CustomSelect = { template: ` <select v-model="selectedValue" required> <option v-for="option in question.options" :value="option"> {{ option }} </option> </select> `, props: ['value', 'question'], computed: { selectedValue: { get() { return this.value }, set(val) { // 触发input事件实现v-model双向绑定 this.$emit('input', val) } } } } const DynamicTemplateComponent = { props: ['value', 'questions'], render(h) { const vm = this return h({ components: { CustomSelect }, props: ['value', 'questions'], template: ` <form> this is a dynamic template <custom-select :question="questions[0]" v-model="value[0]"/>, the template string may change, <custom-select :question="questions[1]" v-model="value[1]"/> </form> ` }, { // 把外层传入的props传递给内部动态组件 props: { value: vm.value, questions: vm.questions }, // 监听内部组件的更新事件,向上透传触发根组件v-model更新 on: { input(newVal) { vm.$emit('input', newVal) } } }) } } const app = new Vue({ el: '#app', components: { DynamicTemplateComponent }, data() { return { questions: [ { options: ['a', 'b', 'c', 'd'] }, { options: [1, 2, 3, 4] } ], // 初始化答案数组保证响应式 answers: [null, null] } } })
HTML模板代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <main id="app"> <dynamic-template-component v-model="answers" :questions="questions"/> <div>已选答案:{{ answers }}</div> </main>
内容的提问来源于stack exchange,提问作者DengSihan
相关产品推荐
相关产品推荐

