我正在开发一个 Vue 项目,其中使用 JS 包,我可以用它来检查单词拼写是否正确。我有一个函数可以将文本分割成单独的单词,然后使用包检查它。然后包返回 true 或 false。
现在我想在用户输入的特定部分下划线以指示拼写错误。 我该怎么做?
<script setup lang="ts">
import { ref, watch } from 'vue';
import Typo from "typo-js";
const inputField = ref('');
const wordsArray = ref<string[]>([]);
//let dictionary = new Typo("en_US", false, false, {dictionaryPath: "../typo/dictionaries/"});
const dictionary = new Typo("en_US");
function extractWords(text: string): string[] {
const cleanText = text.replace(/[.,!?;:]/g, '').toLowerCase();
const words = cleanText.split(/\s+/);
return words.filter(word => word.length > 0);
}
watch(inputField, (newValue) => {
wordsArray.value = extractWords(newValue);
console.log(wordsArray.value[wordsArray.value.length-1]);
const is_spelled_correctly = dictionary.check(wordsArray.value[wordsArray.value.length-1]);
console.log(is_spelled_correctly);
const array_of_suggestions = dictionary.suggest(wordsArray.value[wordsArray.value.length - 1]);
console.log(array_of_suggestions);
});
</script>
<template>
<input type="text" v-model="inputField" />
<div>
</div>
</template>
<style scoped>
</style>
我尝试将错误的单词作为 html 项目返回,但这似乎也不起作用。
要在 Vue.js 输入字段中为拼写错误的单词添加下划线,您可以通过将拼写错误的单词包装在 a 中并应用 CSS 样式进行突出显示来动态修改内容。
以下是如何使用 Typo.js 进行拼写检查来实现此目的的示例:
脚本
<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import Typo from "typo-js";
const inputField = ref('');
const dictionary = new Typo("en_US");
// Helper function to extract words from the input
function extractWords(text: string): string[] {
const cleanText = text.replace(/[.,!?;:]/g, '').toLowerCase();
return cleanText.split(/\s+/).filter(word => word.length > 0);
}
// Function to highlight misspelled words
function highlightText(text: string): string {
const words = extractWords(text);
return words.map(word => {
const isSpelledCorrectly = dictionary.check(word);
if (!isSpelledCorrectly) {
return `<span class="misspelled">${word}</span>`;
}
return word;
}).join(' ');
}
// Computed property to generate highlighted text
const highlightedText = computed(() => {
return highlightText(inputField.value);
});
</script>
模板
<template>
<div>
<input type="text" v-model="inputField" />
</div>
<!-- Render the highlighted text -->
<div v-html="highlightedText"></div>
</template>
CSS
<style scoped>
.misspelled {
text-decoration: underline;
color: red;
}
</style>
说明:
这会在输入内容中用红色强调拼写错误的单词。