- почему мой код CSS не работает в vuejs?
- 3 ответа
- # Локальный (scoped) CSS
- # Использование локальных и глобальных стилей
- # Корневой элемент дочернего компонента
- # Глубокие селекторы
- # Динамически генерируемый контент
- # О чём следует помнить
- Scoped styles don’t apply to v-html injections #749
- Comments
- foundryspatial-duncan commented Mar 28, 2017 •
- Version
- Reproduction link
- Steps to reproduce
- What is expected?
- What is actually happening?
- yyx990803 commented Apr 6, 2017
- Xheldon commented Apr 21, 2017 •
- Scoped CSS Doesn’t work on dynamic content #559
- Comments
- ramakrishnamundru commented Jan 5, 2017
- kazupon commented Jan 7, 2017
- ramakrishnamundru commented Jan 9, 2017
- ramakrishnamundru commented Jan 9, 2017
- kazupon commented Jan 10, 2017 •
- src/components/Hello.vue
- src/assets/LC-switch/lc_switch.js
- ramakrishnamundru commented Jan 10, 2017
- LinusBorg commented Jan 10, 2017 •
- Limitations
- ramakrishnamundru commented Jan 10, 2017
- LinusBorg commented Jan 10, 2017
- ramakrishnamundru commented Jan 11, 2017 •
- ramakrishnamundru commented Jan 17, 2017
- LinusBorg commented Jan 17, 2017 •
- ramakrishnamundru commented Jan 17, 2017
- LinusBorg commented Jan 17, 2017 •
- ramakrishnamundru commented Jan 17, 2017
- LinusBorg commented Jan 17, 2017 •
- ramakrishnamundru commented Jan 17, 2017
- LinusBorg commented Jan 17, 2017
- aboutqx commented May 31, 2018
- ramakrishnamundru commented May 31, 2018
- andredewaard commented Oct 15, 2018
- jrsmith17 commented Feb 13, 2019
- Luke-Wilson commented Feb 14, 2019
- SamuelEarl commented Oct 23, 2019
почему мой код CSS не работает в vuejs?
У меня проблема с CSS в VueJs. Извините за плохое описание, но я понятия не имею, что я делаю не так.
Мой CSS в стиле scoped работает нормально в vuejs, я могу нормально обращаться к idis и классам.
Проблема в том, когда я хочу изменить, например, значение внутреннего CSS элемента vuetify framework или редактора wysiwyg. Я не понимаю, потому что на codepen все работает нормально. Например, здесь я устанавливаю отступ для редактора wysiwig на 0, и он просто работает (в codepen):
На моем vuejs SPA я вставляю точно такой же код CSS, и он ничего не делает. Я в правильном компоненте, адрес правильный элемент. В моей консоли, когда я делаю проверку, я вижу свойства .q1-редактора как отступы 12px и т. Д. Так что на моем сайте ничего не меняется 🙁 Извините за плохое объяснение — css не мой основной язык.
Возможно, кто-то, у кого больше опыта работы с css, поймет, что я делаю неправильно.
3 ответа
В одну сторону
Используйте селектор deep в своих стилях scoped : .container >>> .ql-editor .
Это будет генерировать что-то вроде:
Другой путь
Не используйте scope в своем теге style .
Когда вы используете scoped для тегов стиля в файлах .vue, он добавляет спецификатор атрибута к каждому из ваших селекторов CSS. Когда Vue генерирует HTML для компонента, он добавляет атрибут в HTML, чтобы селекторы совпадали. Поскольку quill генерирует DOM для этого плагина, а не Vue, селекторы не будут совпадать.
Сгенерированный CSS выглядит примерно так:
Но элемент с классом ql-editor не выглядит так, поскольку Vue его не генерировал, поэтому он не будет совпадать:
Это просто выглядит так:
Что вы можете сделать, это иметь несколько тегов
Я бы постарался сохранить селекторы в глобальном стиле настолько уникальными, насколько это возможно, чтобы они не протекали. Вы можете добавить родителя вокруг редакторов и сделать что-то вроде:
Что случилось со мной, так это то, что я не включил тег end , что-то вроде этого может сломать его, поэтому убедитесь, что вы дважды проверили файл vue.
Убедитесь, что вы не забыли включить файл .css, созданный веб-пакетом или чем-то подобным!
Источник
# Локальный (scoped) CSS
Когда у тега есть атрибут scoped , то его CSS будет применяться только к элементам текущего компонента. Это похоже на инкапсуляцию стилей в Shadow DOM. Пользоваться ими можно с некоторыми оговорками, но зато не требуется никаких полифиллов. Это достигается за счёт использования PostCSS для преобразования следующего:
В что-то подобное:
# Использование локальных и глобальных стилей
Вы можете использовать в компоненте локальные и глобальные стилей одновременно:
# Корневой элемент дочернего компонента
С помощью scoped , стили родительского компонента не будут влиять на содержимое дочерних компонентов. Тем не менее, корневой элемент дочернего компонента будет зависеть как от локального CSS из родительского элемента, так и от локального CSS дочернего. Это предусмотрено специально, чтобы родительский элемент мог стилизовать корневой элемент дочернего компонента например для целей стилизации.
# Глубокие селекторы
Если вы хотите, чтобы селектор в scoped стилях был «глубоким», т.е. влиял на дочерние компоненты, вы можете использовать комбинатор >>> :
Указанное выше будет скомпилируется в подобный селектор:
Некоторые пре-процессоры, такие как Sass, не могут правильно обработать >>> . В таких случаях используйте комбинатор /deep/ или ::v-deep — оба псевдонимы для >>> и работают аналогично. На основе примера выше, эти два выражения будут скомпилированы в один и тот же результат:
# Динамически генерируемый контент
DOM-содержимое, создаваемое с помощью v-html не попадает под область действия локальных стилей, но вы всё равно можете его стилизовать с помощью глубоких селекторов.
# О чём следует помнить
Локальные стили не устраняют необходимость классов. Из-за того как браузеры рендерят различные CSS-селекторы, p < color: red >может быть в разы медленнее при использовании в локальных стилях (например, когда комбинируется с селектором по атрибуту). Если же вы используете классы или ID, такие как .example < color: red >, тогда вы практически полностью исключаете ухудшение производительности.
Будьте внимательны с селекторами потомков в рекурсивных компонентах! Для CSS-правила с селектором .a .b , если элемент, который соответствует .a содержит рекурсивный компонент потомок, тогда все .b в этом компоненте потомке будут также соответствовать правилу.
Источник
Scoped styles don’t apply to v-html injections #749
Comments
foundryspatial-duncan commented Mar 28, 2017 •
Version
Reproduction link
Steps to reproduce
- In a single-file Vue component (.vue file), add some scoped styles (with the scoped property on the style tag).
- Inject some HTML that matches your scoped style’s selector with v-html
What is expected?
The styles would affect the injected HTML
What is actually happening?
The styles do not affect the injected HTML
Looks like HTML injected with v-html aren’t given the «data-v-[hash]» property (like data-v-08ce5946).
I think there’s a proposal somewhere to only add the data-v-[hash] to the component’s root element and then prefix all the styles to scope them. That would solve this issue as well.
The text was updated successfully, but these errors were encountered:
yyx990803 commented Apr 6, 2017
Prefixing is simply different from what scoped CSS does. The HTML injected is raw and we are likely not going to change this. You can just give the container element a class and use nested selectors to style the raw HTML.
Xheldon commented Apr 21, 2017 •
There still has a problem.
some info:
«dependencies»: <
«vue»: «^2.2.4»,
«vue-highlightjs»: «^1.2.2»,
«vue-markdown»: «^2.1.3»
>,
«devDependencies»: <
«autoprefixer»: «^6.7.7»,
«babel-cli»: «^6.24.0»,
«babel-eslint»: «^7.2.1»,
«babel-loader»: «^6.4.1»,
«babel-plugin-component»: «^0.9.1»,
«babel-plugin-dynamic-import-node»: «^1.0.1»,
«babel-plugin-syntax-dynamic-import»: «^6.18.0»,
«babel-plugin-transform-runtime»: «^6.23.0»,
«babel-preset-es2015»: «^6.24.0»,
«babel-preset-stage-2»: «^6.22.0»,
«css-loader»: «^0.28.0»,
«eslint»: «^3.19.0»,
«eslint-config-standard»: «^10.0.0»,
«eslint-loader»: «^1.7.1»,
«eslint-plugin-html»: «^2.0.1»,
«eslint-plugin-import»: «^2.2.0»,
«eslint-plugin-node»: «^4.2.2»,
«eslint-plugin-promise»: «^3.5.0»,
«eslint-plugin-standard»: «^2.3.1»,
«eventsource-polyfill»: «^0.9.6»,
«express»: «^4.15.2»,
«extract-text-webpack-plugin»: «^2.1.0»,
«file-loader»: «^0.11.1»,
«friendly-errors-webpack-plugin»: «^1.6.1»,
«html-webpack-plugin»: «^2.28.0»,
«ip»: «^1.1.5»,
«node-sass»: «^4.5.2»,
«ora»: «^1.2.0»,
«progress-bar-webpack-plugin»: «^1.9.3»,
«sass-loader»: «^6.0.3»,
«url-loader»: «^0.5.8»,
«vue-loader»: «^11.3.4»,
«vue-router»: «^2.4.0»,
«vue-style-loader»: «^2.0.5»,
«vue-template-compiler»: «^2.2.6»,
«webpack»: «^2.3.1»,
«webpack-dev-middleware»: «^1.10.1»,
«webpack-hot-middleware»: «^2.18.0»,
«webpack-merge»: «^4.1.0»
>
Omit some unrelated code.
it’s style not work till remove ‘scope’ in style tag.
Should I remove ‘scope’ in style tag or remove ‘‘ in isFocusText?
Источник
Scoped CSS Doesn’t work on dynamic content #559
Comments
ramakrishnamundru commented Jan 5, 2017
When using scoped CSS the styles and the elements are given data- attributes. But when content is added Dynamically it won’t have those data- attributes. So the styles are not applying to the dynamic content.
I think it’s better to add a data- attribute to the root element of the template and add the styles as the children of that attribute instead of adding attributes to individual elements..
The text was updated successfully, but these errors were encountered:
kazupon commented Jan 7, 2017
Thank you for your filling!
Can you provide the minimum reproduction code please?
ramakrishnamundru commented Jan 9, 2017
I don’t know how to reproduce it in a fiddle but look at this image.
here I am using a jquery plugin lc_switch which adds content to replace default checkbox.
the dynamic content is not getting the data- attributes.
so the scoped css styles are not applied
ramakrishnamundru commented Jan 9, 2017
I created a repo showing this issue.
just remove scoped for the plugin css and see changes
kazupon commented Jan 10, 2017 •
Thank you for your codes!
scoped CSS with vue-loader & vue core can not give scopeId to the dynamic content with jQuery etc.
This is hacky even though, you can implement with _scopedId options.
src/components/Hello.vue
src/assets/LC-switch/lc_switch.js
ramakrishnamundru commented Jan 10, 2017
Maybe, But in this way I have to edit most of the plugin files as many will create dynamic content because lc_switch is just an example.
Is in’t there a way to add scopeId to the root of the component and modify the css as the children of the root scopeId. Like:
LinusBorg commented Jan 10, 2017 •
Something like this might work (untested):
Limitations
- If your jQuery plugin adds any DOM Nodes after the component rendered and without any data change in the component triggering this update, the component will not re-render, and the directive will not know about thjis update. You might have to use vm.$forceUpdate() to make it update.
ramakrishnamundru commented Jan 10, 2017
@LinusBorg your code didn’t work for me. the setScopeRecursively function is never executed.
But I think the way of adding scopeId to the root element and modifying CSS accordingly is better solution. Is there a way you can implement this in vue loader.
LinusBorg commented Jan 10, 2017
If you want to use a base base class on the root element and nested styled under it, you don’t need scope, just use a unique classname.
ramakrishnamundru commented Jan 11, 2017 •
@kazupon , @LinusBorg I there a way you can make vue-loader add and remove the style tag for scoped css along with the component i.e style tag added to dom when component created and removed when component destroyed,
Then there will be no such issue even with dynamic content as styles are automatically applied.
If thats not possible then atleast give option to add style tags inside the the template.
ramakrishnamundru commented Jan 17, 2017
@yyx990803 This is clearly a problem because any thing dynamic should have it’s css applied globally. So, It will effect content of other components. So the solution I think of is to move the style tag with scoped attribute into the template, so that it will only appear when its needed. otherwise many jquery plugins css will have to be applied globally, which have a lot of problems.
LinusBorg commented Jan 17, 2017 •
So the solution I think of is to move the style tag with scoped attribute into the template, so that it will only appear when its needed.
That CSS is still being applied globally — it would merely reduce the «risk’s» probability a little, and at worst create a false sense of security because it works as long as two components with matching CSS are not in the document together at the same — until they are, because your changed something in your app — and now you wonder why CSS is screwed up.
So I still don’t see how we could have truly scoped CSS applied by vue-loader for elements that it doesn’t know of, because third party libs create them during runtime.
ramakrishnamundru commented Jan 17, 2017
That CSS is still being applied globally — it would merely reduce the «risk’s» probability a little
If the style tag is removed from the dom then its content is also removed. and no styles will be applied to other components.
There is a discussion here:
angular/angular.js#2387
about style tags. I think it is possible to accommodate dynamic elements css by adding the style tag to template like this:
just bundling all the files with scoped attribute and adding them to template will ensure that the css only comes when required and is removed with the component when switching route.
LinusBorg commented Jan 17, 2017 •
If the style tag is removed from the dom then its content is also removed.
Of course, I don’t deny that. But that CSS is still not scoped to the component, it’s still applied to the whole document.
So if you have two component with conflicting CSS rules in the document at the same time, the CSS will be screwed up even with this method. So as I said above, it’s a small improvement, but the «securtity» that it seems to bring is very brittle.
The ´discussion you linked to doesn’t revolve around scoping issues either, AFAICT,
ramakrishnamundru commented Jan 17, 2017
OK, Now I understand your concern, and the clear meaning of scope.
Then is there any way you can add another mode like «bound» or something else which shows the css loaded is applied globally, but can also be moved with the template hence separating the confusion between the «security» the scoped css provides , and the «flexibility» the bound to the component css provides.
Because it is not just about third party libraries, but many people create dynamic content and the loss of styling to the content is a clear drawback to the loader.
LinusBorg commented Jan 17, 2017 •
Please open a new issue as a featue request with a detailed description of what you want, and why it’s useful. This issue was about scoped CSS, we should start clean.
However, as a disclaimer: I don’t think that his will have a high priority, because (aside from the fact that it’s a very common practice to serve all CSS as one bundle initially) the focus of vue-loader files it to take care of CSS for Vue components, and those can be scoped, so there’s no issue.
Its focus is not to support any kind of dynamic styling for any a third-party lib that might come with its own CSS in the component by some third party lib.
Because it is not just about third party libraries, but many people create dynamic content
I don’t understand what kind of content you refer to here.
ramakrishnamundru commented Jan 17, 2017
I don’t understand what kind of content you refer to here
I mean content like dynamic chat or task manager, editable tables etc..
And thanks I will file a new issue.
LinusBorg commented Jan 17, 2017
I mean content like dynamic chat or task manager, editable tables etc..
Well, either those are created with Vue, so you can use scoped CSS (so you have no problem), or they are created with third-party libs — like jQuery plugins. I don’t see a third possibility that woudl make sense.
aboutqx commented May 31, 2018
I had the same problem,and just give up using scoped .
ramakrishnamundru commented May 31, 2018
andredewaard commented Oct 15, 2018
I have some component that are filled with content from the backend as HTML and will be rendered with v-html . All the tags that are rendered are not getting the data-v-f3f3eg9 attributes and so the scoped styles wont apply on those tags.
jrsmith17 commented Feb 13, 2019
I don’t see a third possibility that woudl make sense.
Vue bills itself as something you can transition into. Not having the scoped css apply to dynamic elements breaks that promise. e.g. when I dynamically add elements with d3. Yes, I can eventually transition to d3 + vue templates, but this means a lot more up front work when Vue should just work out of the box.
Luke-Wilson commented Feb 14, 2019
I tried something similar to @LinusBorg’s setScopeRecursively but this was throwing an error whenever the scopeId started with a letter (e.g v-b9231fa123 as opposed to v-123f1123a). This is because the DOMStringMap needs data attributes to be camelCasified in this instance.
Instead of setting the element’s data attribute using node.dataset[scopeString] = «» as Linus suggested, I used node.setAttribute(‘data-$
Below is my version:
SamuelEarl commented Oct 23, 2019
I am using D3.js inside of Vue.js single file components. I was trying to style some elements that were added to the DOM after the Vue component was created and found that deep selectors work well for this. I wanted to share what I found in the hope that it helps someone.
To apply deep selectors, you start by selecting an element that exists in your tag (e.g., an element), then you add three greater-than symbols ( >>> ), then you select the element that you want to style.
For example, if I want to change the colors of the axes (path) and tick marks (line) in a line chart to blue, then I would use this deep selector:
Notice that I did not select any other child elements that were between the and the
or
elements. When using deep selectors, you only select the parent element that already exists in your tag and then you select the child element that you want to style. You do not select any other child elements that are between those two elements.
This also means that you need to be careful when nesting styles. Make sure that you use the deep selectors properly and that you do not mix up any nested styles with deep selector styles. If you do mix them up, then your deep selector styles probably won’t work.
It is important to note that the
element is two levels below the element and the
element is three levels below the element. So if you are styling multiple child elements with the same set of style rules, then those child elements do not need to be at the same level in the DOM tree.
If you don’t see your deep selector changes in the browser, then refresh it
After saving your style changes, if you don’t see your deep selector styles applied in the browser, then you might need to manually refresh your browser. It appears that the deep selector style changes don’t always trigger a hot reload.
Источник