Home > Enterprise >  vue3 setup - how to access ref element in click event
vue3 setup - how to access ref element in click event

Time:02-03

I use vue3 composition API and <script setup> .

<textarea v-model="textarea"></textarea>
<button @click="showPreview">click</button>
<p ref="p" v-if="open"></p>
const textarea = ref("");
const p = ref(null);
const open = ref(false);

function showPreview() {
  let text = textarea.value.replaceAll(/\n/g, "<br>");
  if (p.value) { // p is null
    p.value.innerHTML = text;
  }

  open.value = true;
}

I want to show textarea's text in p tag(not using v-html) when click button.

But p is null in function...

I tried check p variable in onMounted function but it still null.

onMounted(() => console.dir(p))

How can I access ref element when click event?

Thanks in advance for any help.

CodePudding user response:

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>

CodePudding user response:

One way to display "raw" HTML is to use the v-html directive as per the enter image description here

  • Related