v-bind supports binding variables in a non-template
What problem does this feature solve?
If the value of v-bind is created from setup, the variable cannot be bound
<template>
<el-input v-bind="bind" v-on="{ 'update:modelValue': val => change(val, 'v1') }" />
<el-input v-bind="{ modelValue: data.v1 }" v-on="{ 'update:modelValue': val => change(val, 'v1') }" />
{{ data }}
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const data = ref({ v1: 'test', v2: 'test2' })
const bind = {
// bind a var
modelValue: 'data.v1'
}
const change = (val, key) => {
data.value[key] = val
}
return { data, bind, change }
}
})
</script>
What does the proposed API look like?
We can use : bind variable
<!-- Current -->
<el-input v-bind="{ modelValue: value }" v-on="{ 'update:modelValue': val => (value = val) }"></el-input>
<!-- new -->
<el-input v-bind="{ ':modelValue': 'value' }" v-on="{ 'update:modelValue': val => value = val} " />
<!-- or -->
<el-input v-bind="{ 'v-bind:modelValue': 'value' }" v-on="{ 'update:modelValue': val => value = val} " />
Currently, this can only be done using the function h()
import { defineComponent, h, ref, resolveComponent } from 'vue'
export default defineComponent({
setup() {
const data = ref({ v1: 'test', v2: 'test2' })
return { data }
},
render() {
const props = {
modelValue: this.data.v1,
'onUpdate:modelValue': value => {
this.data.v1 = value
}
}
return h('div', [h(resolveComponent('el-input'), props), h('div', this.data.v1)])
}
})
export default defineComponent({
setup() {
const data = ref({ v1: 'test', v2: 'test2' })
const bind = {
// bind a var
modelValue: computed(() => data.value.v1)
}
const change = (val, key) => {
data.value[key] = val
}
return { data, bind, change }
}
})
@LinusBorg It's not work for computed,you need to rewrap the ref, why? demo