As I'm sure you're aware, escaping is used to include characters literally within text that would otherwise be interpreted as having a special meaning. Establishing which characters have special meaning requires us to look at the 'channels' that will be interpreting that text and then select a suitable escaping mechanism for those channels.
In this case the text will be interpreted by 3 channels...
- As a JavaScript string literal.
- By the Vue template compiler, which has a format very similar to HTML.
- Expressions within the template, such as binding expressions, will be treated as JavaScript, potentially including yet more JavaScript string literals.
JavaScript string literals use the \
character to introduce escape sequences. However, the HTML-like syntax used for Vue templates do not. As for HTML they use entities prefixed with &
.
So, working backwards, we first need to consider how we escape the expressions within the template. In this case that is $emit("enlarge-text")
. As the string "enlarge-text"
doesn't contain any special characters we don't need to apply any escaping. Easy so far.
Then we need to escape the template 'HTML'. Now we do run into problems because the @click
attribute is delimited with double-quotes and its value contains double-quotes. Obviously we could dodge the issue by using different types of quotes but if we instead hit the problem head-on we'd need to use &
entities to escape those quotes. i.e. "
for "
. That gives us:
<button @click="$emit("enlarge-text")">Enlarge text</button>
I believe this is where the escaping in the question goes wrong as it attempts to use \
escaping to escape the attribute value.
If we were using SFCs then that would be sufficient. But for a template written as a string literal we've still got one more level of escaping to apply, using \
. The original quotes around enlarge-text
are no longer present so they don't require any further escaping but we still have the quotes around the attribute. That gives us:
"<button @click=\"$emit("enlarge-text")\">Enlarge text</button>"
However, all that said, the usual conventions when specifying string templates are:
- Use backticks for the template string itself, giving better multi-line support.
- Use double-quotes around attributes.
- Use single-quotes for strings within expressions.
Obviously there are cases where that isn't possible, such as if you want to use backticks within an expression, but if you stick to those conventions as much as possible you usually won't need to escape anything. When you do it'll also be a lot simpler to perform the escaping as you aren't using the same delimiters at all three levels.