[Vuejs]-Vue3 setup โ€“ how to access ref element in click event

3๐Ÿ‘

โœ…

Use v-show so that the element is in the DOM even when not displayed. With v-if, the <p> element is not rendered when open is false, so the ref is null.

<p ref="p" v-show="open"></p>

However, you should consider using a ref to store the text to display instead of working with the actual HTML elements. You can use the <pre> element to preserve whitespace without needing to replace linebreaks with <br>.

<template>
    <textarea v-model="textarea"></textarea>
    <button @click="showPreview">click</button>
    <pre v-if="result">{{result}}</pre>
</template>
<script setup>
import {ref} from 'vue';
const textarea = ref("");
const result = ref("");
function showPreview() {
  result.value = textarea.value;
}
</script>
๐Ÿ‘คUnmitigated

1๐Ÿ‘

One way to display "raw" HTML is to use the v-html directive as per the Vue site.

For example:

<script setup>
import { ref } from 'vue'

const textarea = ref("");
const p = ref(null);
const open = ref(false);
const textToDisplay = ref ("");
  
const showPreview = () => {
  textToDisplay.value = textarea.value.replaceAll(/\n/g, "<br>");
  open.value = true;
}
</script>

<template>
    <textarea v-model="textarea"></textarea>
    <button @click="showPreview">click</button>
    <p v-if="open"><span v-html="textToDisplay"></span></p>
</template>

But be sure to use this with care and to sanitize any data being displayed in this fashion as per this warning about Cross-Site Scripting:

enter image description here

Leave a comment