我想獲取字串輸入并顯示它,還有字串的字符數。
需要幫助來實作。
<section id="app">
<h2>Learn Vue Works</h2>
<input type="text" @input="saveInput">
<button @click="setText">Set Text</button>
<br>
<p>{{ qry }} {{ message }}</p>
=====app.js==============================
const app = Vue.createApp({
data() {
return {
message: 'Vue is great!',
qry: 'Query String : ',
currentSearchInput: '',
};
},
methods: {
setText() {
this.message = this.currentUserInput;
},
saveInput(event) {
this.currentUserInput = event.target.value;
},
},
});
app.mount('#app');
提前致謝。
uj5u.com熱心網友回復:
currentSearchInput使用 v-model將您系結到輸入。你根本不需要saveInput。
<input v-model='currentUserInput' type="text" />
{{currentSearchInput}} {{currentSearchInput.length}}
setText() {
this.message = this.currentSearchInput;
},
您的代碼有currentSearchInput和currentUserInput。錯字?
uj5u.com熱心網友回復:
是的,我同意史蒂文的觀點。不需要使用saveInput函式。只需使用 v-model="currentUserInput" 然后在單擊按鈕時,就這樣設定;
setText() {
this.message = this.currentUserInput;
},
uj5u.com熱心網友回復:
如果你想讓你的用戶控制保存 an 的值<input>,在 Vue 3 中有兩種方法:
- 在輸入元素上使用teplate ref并獲取它
.value:
顯示代碼片段
const { createApp, reactive, toRefs } = Vue;
createApp({
setup() {
const state = reactive({
saved: '',
input: null
});
return {
...toRefs(state),
updateValue: () => { state.saved = state.input.value }
}
}
}).mount('#app')
<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
<div id="app">
<input ref="input" type="search">
<button @click="updateValue">Save</button>
<pre v-text="{ saved, ['saved.length']: (saved && saved.length) || 0 }" />
</div>
- 使用v-model指令
v-model是將表單元素的值雙向資料系結到模型的指令。您可以將模型更新概念化為“即時”(使用input偵聽器完成)。
就像在第一個示例中一樣,您可以保留一個單獨的saved值,并在用戶單擊按鈕時覆寫它:
顯示代碼片段
const { createApp, reactive, toRefs, computed } = Vue;
createApp({
setup() {
const state = reactive({
saved: '',
input: '',
});
const logger = computed(() => ({
...state,
['saved.length']: state.saved.length || 0,
['input.length']: state.input.length || 0
}));
return {
...toRefs(state),
logger,
updateValue: () => { state.saved = state.input }
}
}
}).mount('#app')
<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
<div id="app">
<input v-model="input" type="search">
<button @click="updateValue">Save</button>
<pre v-text="logger" />
</div>
這兩個示例之間的區別在于,在第一個示例中,模型包含對實際<input>元素的參考(讓您可以訪問其所有本機 props 和方法),而在第二個示例中state.input僅包含<input>元素的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/405303.html
標籤:
