Javascript 如何使用vue js绑定组件?
我有表单和选择组件。 事实上事情很简单:我需要两个绑定模型 父组件:Javascript 如何使用vue js绑定组件?,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,我有表单和选择组件。 事实上事情很简单:我需要两个绑定模型 父组件: Vue.component('some-form', { template: '#some-form', data: function() { return { countryNameParent: '' } } }); 包含以下项的子组件: Vue.component('countries', { template:
Vue.component('some-form', {
template: '#some-form',
data: function() {
return {
countryNameParent: ''
}
}
});
包含以下项的子组件:
Vue.component('countries', {
template: '#countries',
data: function () {
return {
items: {
"0": {
"id": 3,
"name": "Afghanistan"
},
"1": {
"id": 4,
"name": "Afghanistan2"
},
"2": {
"id": 5,
"name": "Afghanistan3"
}
},
countryName: ''
}
},
props: ['countryNameParent'],
created: function() {
var that = this;
this.countryName = this.countryNameParent;
},
methods: {
onChange: function (e) {
this.countryNameParent = this.countryName;
}
}
});
我正在使用v-model
合并上述组件。
类似这样的模板:
<template id="some-form">
{{ countryNameParent }}
<countries v-model="countryNameParent"></countries>
</template>
<template id="countries">
<label for="">
<select name="name" @change="onChange" v-model="countryName" id="">
<option value="0">Select the country!</option>
<option v-for="item in items" v-bind:value="item.name">{{ item.name }}</option>
</select>
</label>
</template>
{{countryNameParent}}
选择国家!
{{item.name}
我的目标是获取父组件中的数据以将其发送到服务器(实际形式要大得多),但是我无法在countrynamepent
中获取countryName
的值。此外,如果后继数据不为空,则父级应在后继数据中设置数据
在这里,我尝试了几种方法(请参阅其中的注释部分)。
我知道我需要使用$emit
来正确设置数据,我甚至实现了一个模型,在这个模型中,我将图像作为base64以相同的形式发送,因此我认为解决方案正在接近
另外:我在这里构建了带有图像的示例。这是您的
国家/地区
组件更新,以支持v-model
Vue.component('countries', {
template: `
<label for="">
<select v-model="countryName">
<option value="0">Select the country!</option>
<option v-for="item in items" v-bind:value="item.name">{{ item.name }}</option>
</select>
</label>
`,
data: function () {
return {
items: {
"0": {
"id": 3,
"name": "Afghanistan"
},
"1": {
"id": 4,
"name": "Afghanistan2"
},
"2": {
"id": 5,
"name": "Afghanistan3"
}
},
}
},
props: ['value'],
computed:{
countryName: {
get() { return this.value },
set(v) { this.$emit("input", v) }
}
},
});
Vue.component('countries'{
模板:`
选择国家!
{{item.name}
`,
数据:函数(){
返回{
项目:{
"0": {
“id”:3,
“姓名”:“阿富汗”
},
"1": {
“id”:4,
“名称”:“阿富汗2”
},
"2": {
“id”:5,
“名称”:“阿富汗3”
}
},
}
},
道具:['value'],
计算:{
国家名称:{
get(){返回this.value},
set(v){this.$emit(“input”,v)}
}
},
});
v-model
仅用于设置值
属性和侦听输入
事件。因此,要在任何组件中支持它,组件需要接受值
属性,并发出输入
事件。使用哪个属性和事件是可配置的(有文档记录的)。您只需要正确地实现v-model
。这是你的礼物,我很感激!谢谢