[英]How to access to v-model in custom component
I know we can use a v-model on a vue custom component to bind the value to parent component by this.$emit(input, e.target.value)
.我知道我们可以在 vue 自定义组件上使用 v-model 通过
this.$emit(input, e.target.value)
将值绑定到父组件。 Is there any way we can access the v-model with it's initial value?有什么方法可以访问具有初始值的 v-model 吗?
I already have a upload-button component written.我已经编写了一个上传按钮组件。 The upload-button uploads files upon the file change and server reuturns a new filename / fileID.
上传按钮在文件更改时上传文件,服务器返回一个新的文件名/文件ID。 And that filename / fileID will emit to the parent component with v-model.
并且该文件名 / 文件 ID 将使用 v-model 发送到父组件。
Vue.component('upload-button', {
props: ['endpoint'],
data(){
return ({
filename: 'filename...'
})
},
template: `<label class="upload-button">
<input type="file" accept="image/*" @change="fileSelected" hidden>
<div class="btn btn--outline text--red">
Choose file
</div>
<span>
{{ filename }}
</span>
</label>`,
methods: {
fileSelected(e){
this.filename = e.target.files[0].name;
var formData = new FormData();
formData.append('file', e.target.files[0])
axios.post(endpoint, formData).then(
res=>{
if ( res.data.status ){
this.filename = res.data.fileId;
this.emitVModel(res.data.fileId);
}
}
)
},
emitVModel(id){
this.$emit('input', id)
}
}
})
I am wondering if the file already exist (ie the v-model has an inital value).我想知道该文件是否已经存在(即 v-model 具有初始值)。 How can I access to the existing filename / fileID.
如何访问现有的文件名/文件 ID。
You can access to the v-model via this.$attrs.value
.您可以通过
this.$attrs.value
访问 v-model。
data(){
return ({
filename: this.$attrs.value || 'filename...'
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.