2
<template>
  <div id="body">
    <button type="button" @click="create">Create</button>
  </div>
</template>
<script>
  export default {
    methods: {
      create () {
        let e = document.createElement('input');
        e.classList.add('input-test');
        e.setAttribute('type', 'text');
        e.setAttribute('value', 'test');
        document.getElementById('body').appendChild(e);
      }
    }
  }
</script>
<style scoped>
.input-test {
  color: red;
}
</style>

I tried this code. But input-test style wasn't applied. Why can't apply to element? It works when I remove scoped at style tag.

3 Answers 3

2

I solved by deep selectors deep selectors

Sign up to request clarification or add additional context in comments.

Comments

1

I found the solution here: https://stackoverflow.com/a/49926050/5899698

In the resulting element of createElement you can add the scoped css identifier using:

e.setAttribute(this.$options._scopeId, '');

1 Comment

I've already solved it, but your answer was also very helpful. Thanks a lot.
1

If you look how vue handles style scoping you will see that all elements get a identifier for the scope which will be added to your scoped css. Any new created element won't get transpiled by vue so it doesn't get the needed scoping identifier.

If you only want show an element when the button is clicked you should add it to the dom and only show it on click with the v-if directive

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.