我有一個組件要使用自定義輸入。我正在使用veevalidate,它作業得很好。
但是今天我意識到,當與axios請求一起使用時,我無法設定值。
當設定一個字串或預定義的資料時,它是有效的,比如 this.a = '1' :value="this.a"
<CustomInput
type="text"
name="surname"
placeholder="surname"
:value="'testparam'" // 或者 :value="this.a"
inputClass="form-control form-control-solid h-auto mb-1 mt-2"
/>。
但是,當試圖將值(來自后臺)設定為組件時,沒有任何顯示。
像這樣
data () {
回傳 {
userInfo: {
name: '',
surname: '',
電話: ''
}
}
},
async created () {
await this.axios.get(this.$store.state.baseUrl 'user/personalInfo').then((response) => {
this.userInfo = response.data
console.log(this.userInfo)
})
}
和設定
<CustomInput
type="text"
name="surname"
placeholder="surname"
:value="this.userInfo.name" //什么都不做
inputClass="form-control form-control-solid h-auto mb-1 mt-2"
/>
我試著用 methots 創建了 async 和 normal 創建,但沒有任何變化。
我的CustomInput.vue
<template>
<輸入
:name="name"
:id="name"
:type="型別"
:value="輸入值"
:inputmode="型別"
:placeholder="$t(placeholder)"
:class="[inputClass, { 'has-error': !errorMessage, success: meta.valid }, notRequired ? 'notreq' : '']"
@input="handleChange"
@blur="handleBlur"
maxlength="255"
/>
<p class="help-message" v-show="errorMessage" >
{{errorMessage }}.
</p>
</template>
<script>
從'vee-validate'匯入{ useField }。
出口默認 {
props: {
type: {
型別。字串。
默認: 'text
},
值。{
型別。字串。
默認: ''
},
name: {
型別。字串。
需要: true
},
占位符。{
型別。字串。
默認:''
},
inputClass: {
型別。字串。
默認: ''
},
notRequired: {
型別。Boolean,
默認: false
}
},
setup (props) {
const {
值:輸入值。
errorMessage,
meta,
handleBlur。
handleChange
} = useField(props.name, undefined, {
初始值:props.value
})
回傳 {
errorMessage。
輸入值。
meta,
handleBlur。
handleChange
}
}
}
</script>
<樣式范圍>
輸入 {
背景顏色。#f3f6f9;
color: #3f4254;
padding: 12px;
border-radius: 0.42rem;
寬度:100%。
邊界:無。
}
input::placeholder {
color: #c9c9d4;
font-weight: 400;
}
input:focus-visible {
outline: none;
}
input:focus {
background-color: #ebedf3;
color: #3f4254;
}
.help-message {
margin: 0;
color: #fd6a57;
字體大小: 0.9rem;
font-weight: 400;
width: 100%;
文字對齊:居中。
}
.has-error {
background-image: url("data:image/svg xml,")。)
background-repeat: no-repeat;
background-position: right calc(0.375em 0.325rem) center;
背景尺寸: calc(0.75em 0.65rem) calc(0.75em 0.65rem)。
}
.success {
background-image: url("data:image/svg xml,")。)
background-repeat: no-repeat;
background-position: right calc(0.375em 0.325rem) center;
背景尺寸: calc(0.75em 0.65rem) calc(0.75em 0.65rem);
}
.notreq {
background-image: none !important;
}
.newsletter {
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
</style>
uj5u.com熱心網友回復:
我認為這個問題是因為你的axios請求。在axios請求滿足之前,CustomInput組件用默認的道具渲染,而useForm組合API用空值初始化。
我的解決方案:
你可以在CustomInput組件設定方法中watch值道具。然后每次它的值發生變化時,更新它的值:
此外,你在 你可以在這個 codesandbox 專案中看到我的代碼。
標籤:watch()
watch(
() => props.value,
(newValue, oldValue) => {
console.log("價值道具改變:",newValue)。
inputValue.value = newValue。
}
);
CustomInputprops中有一個問題。嘗試在模板部分發送userInfo.name,而不是this.userInfo.name!
