During the development process using uniapp, we often encounter the need to set the initial value in the input tag. However, due to the special nature of the input tag in uniapp, the ordinary method of setting the initial value does not work. So, how to solve this problem? In this article, we will introduce some methods to dynamically set the initial value of input tags.
Method 1: Use v-model two-way binding
In uniapp, you can use the v-model instruction to achieve two-way binding of data. We can bind the initial value of the input tag to the data. The specific steps are as follows:
<template> <input v-model="value" /> </template> <script> export default { data () { return { value: '' // 用于存储input的初始值 } } } </script>
<script> export default { data () { return { value: '' // 用于存储input的初始值 } }, mounted () { // 通过接口获取要设置的初始值 const initData = 'abc' this.value = initData // 更新value变量 } } </script>
In this way, when the input tag is rendered, the value inside will automatically be set to the initial value stored in the value variable.
It should be noted that when using v-model for two-way binding, you need to ensure that the value attribute of the input tag exists. Therefore, a default value can be set within the input tag, otherwise unexpected results will occur.
Method 2: Use ref reference
In addition to v-model two-way binding, you can also use ref reference to dynamically set the initial value of the input tag. The specific steps are as follows:
<template> <input ref="myInput" /> </template>
<script> export default { mounted () { const initData = 'abc' this.$refs.myInput.value = initData // 设置input标签的初始值 } } </script>
In this way, when the input tag is rendered, the value inside will be dynamically set to the initial value we want.
It should be noted that when using ref reference to set the initial value of the input tag, it needs to be used in the mounted hook function. Because this is the moment when the component completes rendering, the ref reference can get the real DOM node.
Summary
In uniapp, through v-model two-way binding and ref reference, we can easily set the initial value of the input tag dynamically. The specific method can be selected according to the actual situation. Hope this article is helpful to everyone!
The above is the detailed content of How to dynamically set initial value using input tag in uniapp. For more information, please follow other related articles on the PHP Chinese website!