我正在尝试在创建时为某些输入组件设置初始值,然后在单击按钮后,如果它们被更改,则获取这些值。
这适用于设置初始值:
<template>
<div class="editUserInfo">
<input type="text" id="acName">
<input type="text" id="acUsername">
<input type="text" id="acEmail">
<button v-on:click.prevent="updateInfo">Update</button>
</div>
</template>
<script>
data(){
return{
tokenExists: false,
userCookie: {
id: '',
secret: '',
expire_at: ''
},
newUserInfo: {
nuName: '',
nuUsername: '',
nuEmail: '',
},
actualUserInfo: {
acName: '',
acUsername: '',
acEmail: '',
}
}
},
methods: {
checkToken(){
if (this.$cookie.get('secret') == null){
this.tokenExists = false;
}else{
this.tokenExists = true;
var userInfo = JSON.parse(this.$cookie.get('secret'));
this.id = userInfo.user_id;
this.secret = userInfo.secret;
this.expire_at = userInfo.expire_at;
this.acName = userInfo.name;
this.acUsername = userInfo.username;
this.acEmail = userInfo.email;
}
},
mounted(){
document.getElementById("acName").value = this.acName;
document.getElementById("acUsername").value = this.acUsername;
document.getElementById("acEmail").value = this.acEmail;
}
...
</script>
但是,当我单击按钮时,我需要输入组件中的v-model属性来获取这些值。当我添加v-model属性时,值会被正确初始化,但是当我通过更改其中一个组件的值来测试组件时,其他输入组件将被清除。
这不起作用:
<template>
<div class="editUserInfo">
<input type="text" id="acName" v-model="newUserInfo.nuName">
<input type="text" id="acUsername" v-model="newUserInfo.nuUsername">
<input type="text" id="acEmail" v-model="newUserInfo.nuEmail">
<button v-on:click.prevent="updateInfo">Update</button>
</div>
</template>
认为这是丢失变量的问题,但我测试了在控制台中打印它们并且它们没有改变或未定义。
答案 0 :(得分:0)
无需使用document.getElementById我们可以使用数据部分绑定到v-model
<template>
<div class="editUserInfo">
<input type="text" id="acName" v-model="newUserInfo.nuName">
<input type="text" id="acUsername" v-model="newUserInfo.nuUsername">
<input type="text" id="acEmail" v-model="newUserInfo.nuEmail">
<button v-on:click.prevent="updateInfo">Update</button>
</div>
</template>
在您的脚本部分
<script>
data(){
return{
tokenExists: false,
userCookie: {
id: '',
secret: '',
expire_at: ''
},
newUserInfo: {
nuName: '',
nuUsername: '',
nuEmail: '',
},
actualUserInfo: {
acName: '',
acUsername: '',
acEmail: '',
}
}
},
mounted(){
this.newUserInfo.nuName = 'somevalue'
this.newUserInfo.nuUsername = 'somevalue
this.newUserInfo.acEmail = 'somevalue'
}
在'somevalue'中给出你喜欢的东西,在方法checkToken()中也使用它像mount()