stk*_*tix 6 javascript vue.js vuejs2
如何在 Vue.js 中将父模型绑定到子模型?
下面的这些代码工作正常。如果我手动填写输入,则子模型将其值返回给父模型。
但问题是,如果来自父 AJAX 请求的数据集,输入不会自动填充。
谁可以帮我这个事?
表单.vue
<template>
<form-input v-model="o.name" :fieldModel="o.name" @listenChanges="o.name = $event"/>
<form-input v-model="o.address" :fieldModel="o.address" @listenChanges="o.address = $event"/>
</template>
<script>
import FormInput from '../share/FormInput.vue'
export default {
data () {
return {
o: {
name: '',
address: ''
}
}
},
components: { 'form-input': FormInput },
created: function() {
axios.get('http://api.example.com')
.then(response => {
this.o.name = response.data.name
this.o.address = response.data.address
})
.catch(e => { console.log(e) })
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
表单输入.vue
<template>
<input type="text" v-model='fieldModelValue' @input="forceUpper($event, fieldModel)">
</template>
<script>
export default {
props: ['fieldModel'],
data() {
return {
fieldModelValue: ''
}
},
mounted: function() {
this.fieldModelValue = this.fieldModel;
},
methods: {
forceUpper(e, m) {
const start = e.target.selectionStart;
e.target.value = e.target.value.toUpperCase();
this.fieldModelValue = e.target.value.toUpperCase();
this.$emit('listenChanges', this.fieldModelValue)
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
如果您利用v-model组件,事情会变得更加简单。
如果您放置v-model一个组件,该组件应该采用名为 的 prop value,并且应该发出input事件来触发其更新。
我喜欢创建一个computed来隐藏事件发出,并允许我只在我的组件v-model内部computed。
new Vue({
el: '#app',
data: {
o: {
name: '',
address: ''
}
},
components: {
'form-input': {
template: '#form-input',
props: ['value'],
computed: {
fieldModelValue: {
get() {
return this.value;
},
set(newValue) {
this.$emit('input', newValue.toUpperCase());
}
}
}
}
},
// Simulate axios call
created: function() {
setTimeout(() => {
this.o.name = 'the name';
this.o.address = 'and address';
}, 500);
}
});Run Code Online (Sandbox Code Playgroud)
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
Name ({{o.name}})
<form-input v-model="o.name"></form-input>
Address ({{o.address}})
<form-input v-model="o.address"></form-input>
</div>
<template id="form-input">
<input type="text" v-model='fieldModelValue'>
</template>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6408 次 |
| 最近记录: |